Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is replacing the value of a member variable thread safe?

In my application (written in C#) I have an instance of a class with a member variable that points to an instance of another class. This second instance is read-only, so the state of that instance will never change once it is created. But on some occasions I want to replace this instance with a new and updated instance. Is replacing this reference in the first instance safe in a multithreaded environment? Or can this cause a problem?

like image 805
svb Avatar asked Mar 23 '12 13:03

svb


2 Answers

Yes, it is "safe" in the sense that the reference read/write is atomic. Your client code will always get a valid instance.

Obviously you cannot guarantee that the client code will get the new instance immediately.

like image 99
GazTheDestroyer Avatar answered Oct 06 '22 01:10

GazTheDestroyer


No, it's not thread-safe because of cache (some architectures needs a memory barrier for something like this), for compiler optimizations and for concurrent access.
You have following choices:

  • Declare that field as volatile.
  • Use Interlocked.Exchange() to replace the value.

Read MSDN documentation to choose what's better for you (quick: volatile should be faster but you can't save the old value and write the new one in one atomic operation).

EDITED
I think I have to make clear what I mean (many people seem to consider atomic a synonym of thread-safe):

Is replacing this reference in the first instance safe in a multithreaded environment?

No, strictly speaking it's not thread-safe. You don't know what will happen so it can't be safe.

Or can this cause a problem?

It depends on the context. If one thread won't use the correct socket connection (or a closed one) then it'll be a big problem. If one thread won't use the right color for formatting its output then it may not be a problem.

like image 34
Adriano Repetti Avatar answered Oct 06 '22 00:10

Adriano Repetti