Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a bool read/write atomic in C#

Is accessing a bool field atomic in C#? In particular, do I need to put a lock around:

class Foo {    private bool _bar;     //... in some function on any thread (or many threads)    _bar = true;     //... same for a read    if (_bar) { ... } } 
like image 678
dbkk Avatar asked Sep 12 '08 16:09

dbkk


People also ask

Does bool need to be atomic?

You need atomic<bool> to avoid race-conditions. A race-condition occurs if two threads access the same memory location, and at least one of them is a write operation. If your program contains race-conditions, the behavior is undefined.

Is Boolean thread safe C#?

None of these are thread-safe. The thread that calls the getter will always read a stale value. How stale it is depends on the processor and the optimizer.

What is atomic operation in C#?

Atomic operations are "indivisible" operations, which cannot be divided, e.g., interrupted. Microprocessors do not execute sequentially, that is, instruction after instruction, just like written in a program. There are external objects, which can change execution flow. A good example are interrupts.


2 Answers

Yes.

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.

as found in C# Language Spec.

Edit: It's probably also worthwhile understanding the volatile keyword.

like image 113
Larsenal Avatar answered Oct 28 '22 16:10

Larsenal


As stated above, bool is atomic, but you still need to remember that it also depends on what you want to do with it.

if(b == false) {     //do something } 

is not an atomic operation, meaning that the value of b could change before the current thread executes the code after the if statement.

like image 23
Dror Helper Avatar answered Oct 28 '22 16:10

Dror Helper