Why doesn't Interlocked.Exchange support the Boolean type?

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

One use case is when you want to guarantee that some code is executed only once, and you want to use a logical flag for this.

+47
multithreading c #
May 28 '11 at 22:34
source share
2 answers

Yes, there is a good reason. Interlocked methods require low-level support at the processor level. For example, see this answer . This is a problem when you define a structure that does not have agnostic architecture.

Implementing the low-blocking technologies supported by the Interlocked class for data types that are part of the processor word size is difficult. RISC's approach to processor design, which was popular 10 years ago, did not greatly encourage it. The mismatch between the size of the operand and the bus width of its own memory makes it very difficult to implement. One of the reasons Intel x86 architecture is still on your lap is survival for 30 years without using shortcuts. Learn more about RISC in this wikipedia article .

+47
May 29 '11 at 1:16
source share

Without answering the question, but as a workaround, you can just use int instead of bool, as 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. } 

PS If there is evidence that reading is faster than writing, then Interlocked.CompareExchange may be better for this case (only once, and I accept many more than the first).

+8
Jun 25 '14 at 17:25
source share



All Articles