I’ve got some multi threaded code I’d like to increase the performace of a bit, so I’m wondering if I can get rid of a lock.
I’ve got a field member:
private IList<ServerStatus> status;
It’s updated in a thread like so:
status = GetUpdatedStatus();
And it’s used in another thread like this:
var currentStatus = status;
So the question is, can the above yield any problems without locks around the two assignment statements ?
I guess the only scenario I can see is currentStatus being null, but then again I’d expect an assignment to be somewhat thread-safe (either it has changed the reference or not)
You are right. You will see the assignment or you won’t see it. Assignments (and reads) of references are always “atomic” (in the end it’s because on 32 bits machines references are 32 bits, so can be done atomically, and on 64 bits machines (running a 64 bits app) references are 64 bits, so can be done atomically. The only exception is trying to write/read a long (64 bits) on a 32 bits machine. There you would have to use Interlocked.Read / Interlocked.Exchange)
Normally should declare status as
volatile, so that each thread sees only the latest version. You should read this: http://www.albahari.com/threading/ it’s very very good!If you don’t trust me, read the section
Do We Really Need Locks and Barriers?here http://www.albahari.com/threading/part4.aspxAh… I was forgetting… The world HATES you, so there is a little thing to know of volatile: sometimes it doesn’t work 🙂 🙂 Read, in the same page of the other example, the section
The volatile keyword, the part UNDER the red box.Notice that applying volatile doesn’t prevent a write followed by a read from being swapped, and this can create brainteasers. In the end, the only way to be sure is to useInterlocked.Exchangeto write andInterlocked.CompareExchangeto read something OR protect the read and the write sections with synchronization (likelock) OR fill your program with Thread.MemoryBarrier (but don’t try it, you’ll fail, and you won’t even know why). You are guaranteed that all the reads and the writes done in the lock will be done IN the lock, not before or after.