Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET C# Multithreading

Question about threading to satisfy my curiosity...

Let's say I have static variable _status (ProgressStatus) and many threads are reading from this. To update this static variable I use an immutable object ProgressStatus, create a new instance and then swap out the reference.

var status = new ProgressStatus (50, "Working on it"); //plus many more fields in constructor

lock (_statusLocker) _status = status; // Very brief lock

Here's the reader code

public GetProgressStatus () {

     var status = new ProgressStatus (_status.ID, _status.Description); 
     return status }

What's the worst that could happen if I don't apply the lock?

like image 965
Mark 909 Avatar asked Nov 26 '10 14:11

Mark 909


1 Answers

It's possible that other threads won't see the new value.

Indeed, unless they're locking too, it's still possible that they won't see the new value.

Even though the reference will updated atomically (i.e. it'll never be some value which is a mixture of the old and new values), that says nothing about when the change becomes visible to other threads - or when other threads will even bother checking. (For example, one thread may have cached the value in a register, and without any indication that the thread needs to check main memory, it may not do so.)

It's possible that by declaring the variable as volatile you'll avoid this - but I've stopped believing that I understand exactly what volatile means, to be honest.

Using a lock consistently when working with shared mutable data (reading or writing) makes this problem go away due to the semantics of locking. Doing it in a lock-free and guaranteed-correct way involves considerably deeper understanding of what's going on. (Note that it's the variable which is mutable here, even if the object it refers to isn't.)

like image 174
Jon Skeet Avatar answered Oct 17 '22 03:10

Jon Skeet