Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Interlocked.Exchange not support Boolean type?

Is there some practical reason why the .NET team decided not to support Boolean in Interlocked.Exchange operation?

One of the usage examples is when you want to guarantee that some code is executed only once and you want to use a Boolean flag for that.

like image 707
Dennis Avatar asked May 28 '11 22:05

Dennis


People also ask

Is interlocked exchange thread safe?

The Interlocked class provides a number of static methods that perform atomic operations. These can generally be regarded as thread-safe.

What is interlocked exchange?

Interlock. Exchange returns the original value while performing an atomic operation. The whole point is to provide a locking mechanism. So it is actually two operations: read original value and set new value. Those two together are not atomic.

What is the value of the bool?

The default value of the bool type is false .

Is bool Atomic C#?

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.


2 Answers

Yes, there is a good reason. The implementation of the Interlocked methods requires low-level support at the processor level. See this answer for example. That's an issue when you define a framework that's architecture agnostic.

Implementing the low-lock techniques supported by the Interlocked class on data types that are a fraction of the native processor word size is difficult. The RISC approach to cpu design that was popular 10+ years ago discouraged it strongly. The mismatch between operand size and native memory bus width makes it very hard to implement. One reason that Intel's x86 architecture is still on your lap, surviving 30 years already by not taking the shortcuts. More background info on RISC in this wikipedia article.

like image 151
Hans Passant Avatar answered Sep 17 '22 17:09

Hans Passant


Not answering the question, but as a workaround you can just use int instead of bool the way C does.

    int m_IsFirstTime = 1; // 1 means true 0 means false.       void SomeMethod()     {         if (1 == Interlocked.Exchange(ref m_IsFirstTime , 0))             // Do something for the first time.          else             // Do something for all other times.      } 

P.S. If there is evidence that read is faster than write then Interlocked.CompareExchange might be better for this case (only one first time and I assume a lot of non first).

like image 44
ILIA BROUDNO Avatar answered Sep 17 '22 17:09

ILIA BROUDNO