Is the "switch" statement evaluation thread-safe?
Consider the following sample code:
class MyClass
{
public long x;
public void DoWork()
{
switch (x)
{
case 0xFF00000000L:
// do whatever...
break;
case 0xFFL:
// do whatever...
break;
default:
//notify that something going wrong
throw new Exception();
}
}
}
Forget the uselessness of the snippet: my doubt is about the behavior of the switch
statement.
Suppose that the x
field could have only two values: 0xFF00000000L
or 0xFFL
. The switch above should not fall into the "default" option.
Now imagine that one thread is executing the switch with "x" equal to 0xFFL, thus the first condition won't match. At the same time, another thread modifies the "x" variable to 0xFF00000000L. We know a 64-bit operation is not atomic, so that the variable will have the lower dword zeroed first, then the upper set afterward (or vice versa).
If th开发者_StackOverflow社区e second condition in the switch will be done when the "x" is zero (i.e. during the new assignment), will we fall into the undesired "default" case?
Yes, the switch
statement itself, as shown in your question, is thread-safe. The value of field x
is loaded once into a (hidden) local variable and that local is used for the switch
block.
What isn't safe is the initial load of the field x
into a local variable. 64-bit reads aren't guaranteed to be atomic, so you could be getting stale and/or torn reads at that point. This could easily be resolved by using Interlocked.Read
, or similar, to explicitly read the field value into the local in a thread-safe way:
long y = Interlocked.Read(ref x);
switch (y)
{
// ...
}
You're actually posting two questions.
Is it threadsafe?
Well, obviously it is not, another thread might change the value of X while the first thread is going into the switch. Since there's no lock and the variable is not volatile you'll switch based on the wrong value.
Would you ever hit the default state of the switch?
Theoretically you might, as updating a 64 bits is not an atomic operation and thus you could theoretically jump in the middle of the assignment and get a mingled result for x as you point out. This statistically won't happen often but it WILL happen eventually.
But the switch itself is threadsafe, what's not threadsafe is read and writes over 64 bit variables (in a 32 bit OS).
Imagine instead of switch(x) you have the following code:
long myLocal = x;
switch(myLocal)
{
}
now the switch is made over a local variable, and thus, it's completely threadsafe. The problem, of course, is in the myLocal = x
read and its conflict with other assignments.
C#'s switch statement isn't evaluated as a series of if conditions (as VB's can be). C# effectively builds up a hashtable of labels to jump to based on the value of the object and jumps straight to the correct label, rather than iterating through each condition in turn and evaluating it.
This is why a C# switch statement doesn't deteriorate in terms of speed as you increase the number of cases. And it's also why C# is more restrictive with what you can compare to in the switch cases than VB, in which you can do ranges of values, for example.
Therefore you don't have the potential race condition that you've stated, where a comparison is made, the value changes, the second comparison is made, etc, because there is only one check performed. As for whether it's totally threadsafe - I wouldn't assume so.
Have a dig with reflector looking through a C# switch statement in IL and you'll see what's happening. Compare it to a switch statement from VB which includes ranges in the values and you'll see a difference.
It's been quite a few years since I looked at it, so things may have changed slightly...
See more detail about switch statement behaviour here: Is there any significant difference between using if/else and switch-case in C#?
As you already assumed, the switch statement is not thread-safe and might fail in certain scenarios.
Furthermore, using lock
on your instance variable won't work neither, because the lock
statement expects an object
causing your instance variable to be boxed. Every time the instance variable is boxed, a new boxed variable will be created, making the lock
effectively useless.
In my opinion you have several options solving this issue.
- Use
lock
on a private instance variable of any reference type (object
will do the job) - Use
ReaderWriterLockSlim
to let multiple threads read the instance variable but only one thread write the instance variable at a time. - Atomically store the value of the instance variable to a local variable in your method (e.g. using
Interlocked.Read
orInterlocked.Exchange
) and perform theswitch
on the local variable. Note that this way you might use the old value for theswitch
. You have to decide if this can cause problems in your concrete use-case.
精彩评论