Why are locks used here?

I am currently reading the Joe Albahari Threading e-book in C # , and sometimes in my code example, it uses locks in places where I do not see any thread's security problem. Here , for example, it blocks writing and reading from the _status field, which refers to an immutable object.

I understand that if the ProgressStatus class was changed, you would need to block its reading and writing, because if one thread was previously missed between updating the PercentComplete and StatusMessage fields with another thread reading the status, the second thread may receive an invalid pair of values ​​for these fields. (100% complete / "Operation in progress ...")

But since ProgressStatus is unchanged, such an invalid status cannot be. If Joe removed both of these locks, what thread safety issue could arise?

+5
source share
2 answers

If Joe removed both of these locks, what thread safety issue could arise?

This can lead to "outdated data", the read code can cache it and see only the old value.

This use of lock is typical, it benefits from the side effect of lock : it has an implied memory barrier and prevents the old copy from being viewed. You would more often see that volatile ProgressStatus _status; but volatile also has its problems.

You are right that the actual read and write operations do not require a complete lock here (the absence of a link is atomic).

+4
source

Readers may never be able to see _status update to a new value. All reads can be collapsed into one physical read.

Also, I think you might see partially initialized objects if _status was passed into memory before the fields in the referenced object.

Note that this lock has nothing to do with the referenced object. It's about protecting the link itself.

Access to a variable in multiple threads, when one of the calls is a record, is a data race. All sorts of things can happen. What I said above are just examples.

+4
source

Source: https://habr.com/ru/post/1209626/


All Articles