Is the “switch” statement evaluation thread-safe?

后端 未结 4 737
南方客
南方客 2021-02-05 04:04

Consider the following sample code:

class MyClass
{
    public long x;

    public void DoWork()
    {
        switch (x)
        {
            case 0xFF00000000         


        
4条回答
  •  没有蜡笔的小新
    2021-02-05 05:00

    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.

提交回复
热议问题