Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are locks used here?

I am currently reading Joe Albahari's Threading in C# e-book, and sometimes in his example code, he uses locks in places where I don't see any thread safety issue. Here, for example, he locks around writing to and reading from the _status field, which refers to an immutable object.

I understand that if the ProgressStatus class were mutable, you would need to lock around reading from and writing to it, because if one thread were pre-empted in between updating the PercentComplete and StatusMessage fields by another thread reading the status, the second thread might get an invalid pair of values for those fields. (100% complete / "Operation in progress...")

But since ProgressStatus is immutable, no such invalid status can occur. If Joe removed both of those locks, what thread safety issue could arise?

like image 470
dgmulf Avatar asked Dec 20 '14 22:12

dgmulf


1 Answers

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

It could lead to 'stale data', the reading code could cache it and only see an old value.

This usage of lock is a-typical, it is profiting from a side-effect of lock: it has an implied memory-barrier, and that prevents seeing an old copy. You would more usally see a volatile ProgressStatus _status; but volatile has its issues too.

You are right that the actual read and write operations don't reallly need a lock here (acessing a reference is atomic).

like image 56
Henk Holterman Avatar answered Oct 19 '22 10:10

Henk Holterman