Parallel and The C# Memory Model
Parallel programming can be tricky, both compiler and CPU’s optimization can lead into a twilight zone’s debugging.
lets take the following code snippet snippet:
can you predict the outcome?
will it ever reach the completion at line 24?
you can download the snippet from here.
now download the snippet and try to execute it in the following order:
- Compiled in Debug mode and double click on the exe file (without an attached debugger).
- Compiled in Release mode and double click on the exe file (without an attached debugger).
- Compiled in Release mode and run it F5 (with an attached debugger).
so why does is execute predictably in Debug mode, while behaving quit strange in Release mode?
even stranger why does it execute predictably in Release mode when a debugger attached?
what happening is a matter of a single thread optimization that can occurs at the compiler (JIT) or CPU level which is taking assumption which is not acceptable for parallel execution.
it can be fixed up using different API like Thread.MemoryBarrier and other.
the optimization world is still rely on a single thread assumption (with some special instruction for parallel execution).
while the computing world becoming more parallel each day, this single thread assumption priority may have to be change in the future.
in order to avoid pitfalls, you should be aware o it and use a parallel dedicated APIs.