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) { ... } }
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.
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.
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.
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.
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.
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