I'm wondering if this is completely thread-safe and whether or not the volatile keyword should be in place.
using System.Threading; class Program { private static volatile bool _restart = true; private static void Main() { while (_restart) { // Do stuff here every time for as long as _restart is true Thread.Sleep(1); } } private static void SomeOtherThread() { Thread.Sleep(1000); _restart = false; } }
I think it is, but I want to double check, since I'm not 100% certain I just want to be sure.
I think the volatile keyword is required because then it would never be possible to have the value cached in registers or alike optimizations.
Updating a bool is always thread safe, if you never read from it. And if you do read from it, then the answer depends on when you read from it, and what that read signifies. On some CPUs, but not all, writes to an object of type bool will be atomic. x86 CPUs will generally make it atomic, but others might not.
Therefore, the volatile keyword does not provide thread safety when non-atomic operations or composite operations are performed on shared variables. Operations like increment and decrement are composite operations.
From what I have read (click) atomicity of bool does not guarantee it will be thread safe. Will then volatile type help? None of these are thread-safe. The thread that calls the getter will always read a stale value.
In Java volatile creates a memory barrier when it's read, so it can be used as a threadsafe flag that a method has ended since it enforces a happens-before relationship with the code before the flag was set. This is not the case in C.
What SLaks answered is correct, of course, but to answer your question: yes on both counts: it is safe, it should be declared volatile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With