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?
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.
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:
volatile
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With