1

EDIT: I've finally written a complete article about the issue: Synchronization, memory visibility and leaky abstractions


I'm demonstrating the importance of volatile read with this code:

bool ok = false;

void F()
{
    int n = 0;
    while (!ok) ++n;
}

public void Run()
{
    Thread thread = new Thread(F);
    thread.Start();

    Console.Write("Press enter to notify thread...");
    Console.ReadLine();

    ok = true;

    Console.WriteLine("Thread notified.");
}

As expected the thread is not aware of the new ok value and the program hangs.

But to obtain this behavior I have to do something in the while loop, e.g. incrementing an integer.

If I remove the ++n statement, the thread reads the new value and exits.

I guess it has something to do with the JITter optimizations because as far as CIL is concerned there is nothing (at least for a layman like me):

.method private hidebysig instance void  F() cil managed
{
  .maxstack  2
  .locals init ([0] int32 n)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  br.s       IL_0008
  IL_0004:  ldloc.0
  IL_0005:  ldc.i4.1
  IL_0006:  add
  IL_0007:  stloc.0
  IL_0008:  ldarg.0
  IL_0009:  ldfld      bool ThreadingSamples.MemoryVisibilitySample::ok
  IL_000e:  brfalse.s  IL_0004
  IL_0010:  ret
}


.method private hidebysig instance void  F() cil managed
{
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldfld      bool ThreadingSamples.MemoryVisibilitySample::ok
  IL_0006:  brfalse.s  IL_0000
  IL_0008:  ret
}

And, on the contrary, I would naively expect that doing something in the loop would increase the odds for the thread to trigger a cache refresh.

What am I missing again?


FINAL EDIT: this is again some JITter black-magic.

Kudos to Hans for confirming this is a "well-known" JITter "issue" and for pointing out that in x64 we get the "expected" behavior.

Kudos to MagnatLU for providing the resulting assembly code and for sharing some debugging wisdom.

6
  • This is well-known behavior of the x86 jitter. Won't happen when you use the x64 jitter. Doesn't have much to do with the jitter, a bool is not a synchronization object. Nov 23, 2013 at 21:31
  • What is the question? Your question mentions "volatile read", but you're not actually doing that, so what is the question really? Nov 23, 2013 at 21:39
  • @HansPassant: Thanks for the quick answer. Indeed in x64 the behavior is "correct" without ++n. Any more info on the why and how? Something to do with the x86 and x64 memory models or a pure CLR thing? PS: please Hans don't assume that what you know is "well-known", your answers show that you know far more than the average layman. ;)
    – Pragmateek
    Nov 23, 2013 at 21:39
  • @LasseV.Karlsen: I'm just showing that without volatile read you can get in trouble. It's to demonstrate the memory visibility concept and how why it's a use-case for the volatile modifier. :)
    – Pragmateek
    Nov 23, 2013 at 21:41
  • My point is that your question is this: "What am I missing again?". Then you have already hinted at the solution here, use a volatile read. So my question still stands: What is your question? You're saying: A is a problem, and when describing A you're hinting at B, which would solve A, then you ask "What am I missing?". The only real answer here is "Nothing, using a volatile read would solve that problem". So again, what is the question? Nov 23, 2013 at 21:43

1 Answer 1

3

As you wrote, it's all in the JITter. In Release build and without debugger attached, with ++n you get:

            int n = 0;
00000000  push        ebp 
00000001  mov         ebp,esp 
            while (!ok) ++n;
00000003  movzx       eax,byte ptr [ecx+4] 
00000007  test        eax,eax 
00000009  jne         0000000F 
0000000b  test        eax,eax      ; <---
0000000d  je          0000000B     ; <---
0000000f  pop         ebp 
        }
00000010  ret 

And without ++n:

            while (!ok) ;
00000000  push        ebp 
00000001  mov         ebp,esp 
00000003  cmp         byte ptr [ecx+4],0 
00000007  je          00000003 
00000009  pop         ebp 
        }
0000000a  ret 

The real question should be why there is no code for ++n emitted at all.

Edit: on x64 Release build results are similar:

            Debugger.Break();
00000000  push        rbx 
00000001  sub         rsp,20h 
00000005  mov         rbx,rcx 
00000008  call        FFFFFFFFED0EE4D0 
0000000d  mov         ecx,2710h 
00000012  call        FFFFFFFFEDCFE460 
            while (!ok) ++n;
00000017  mov         al,byte ptr [rbx+8] 
0000001a  movzx       ecx,al 
0000001d  test        ecx,ecx 
0000001f  jne         0000000000000025 
00000021  test        ecx,ecx 
00000023  je          0000000000000021 
00000025  add         rsp,20h 
00000029  pop         rbx 
0000002a  rep ret 
5
  • Hmm interesting, so with ++n it uses a register, whereas without it reads "directly" from memory. Thanks for taking the time to extract the native code; with some WinDBG trickery I guess? :) Thanks.
    – Pragmateek
    Nov 23, 2013 at 21:54
  • 1
    @Pragmateek actually its quite easy to do right in visual studio, just pause your program while it is running and go to Debug->Windows->Dissasembly and it will show you the the assembled code that the JITer created. Nov 23, 2013 at 21:56
  • 2
    All done in VS. You have to trick .NET to use the right JITter. Even starting Release build from VS still uses non-optimizing compiler. You have to run Release build directly and either attach VS to running process after your method has been jitted or place Debugger.Break(); in your method of interest and allow OS to attach VS to it for you.
    – MagnatLU
    Nov 23, 2013 at 21:57
  • 1
    @Scott Chamberlain most important part is that you can't run your program from VS (or with any other debugger attached). You have to attach debugger after native code has beed emitted.
    – MagnatLU
    Nov 23, 2013 at 21:58
  • @ScottChamberlain: thanks. This is what I used for "normal" code but running from VS has often strange side effects.
    – Pragmateek
    Nov 23, 2013 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.