Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this (volatile bool) always thread safe?

Tags:

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.

like image 943
Aidiakapi Avatar asked Jan 08 '12 17:01

Aidiakapi


People also ask

Is volatile bool thread safe?

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.

Does volatile ensure thread safety?

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.

Is reading a bool thread safe?

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.

Is volatile thread safe C?

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.


1 Answers

What SLaks answered is correct, of course, but to answer your question: yes on both counts: it is safe, it should be declared volatile.

like image 105
Mike Nakis Avatar answered Sep 19 '22 13:09

Mike Nakis