Reputation: 13938
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)
Upvotes: 15
Views: 2822
Reputation: 111850
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.aspx
Ah... 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 use Interlocked.Exchange
to write and Interlocked.CompareExchange
to read something OR protect the read and the write sections with synchronization (like lock
) 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.
Upvotes: 22
Reputation: 1062745
Reference writes are guaranteed atomic, so there are only really two things to check:
volatile
if you need to notice the changeInterlocked.CompareExchange
to make sure you don't lose data; keep reapplying your change until you win the swapi.e.
object snapshot, newValue;
do
{
snapshot = field;
// do something based on that; create a clone
// with more/less data for example
newValue = ...;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref field, newValue, snapshot), snapshot));
Upvotes: 6