问题
I've been reading through ThreadLocal<T>
implementation and don't quite understand the rationale behind inverting an int id before storing it in a private int filed (m_idComplement
) and then inverting it back again in almost every expression it's used in. Except for this case applicable to JavaScript, I can't find any information on why would double negation be useful in C#?
On line 240 it does assign 0 without negation, but it could've just assigned a -1 and just drop all the other unnecessary ones, no?
https://dl.dropboxusercontent.com/u/65419748/ThreadLocal.cs
https://i.imgur.com/3z3F64V.png

回答1:
The reference source for ThreadLocal.cs
contains the following comment against this field:
Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or possibly due to a memory model issue in user code.
They're essentially switching the default, uninitialized value of the ID from 0, which it would be if stored directly as an int
field, to -1.
来源:https://stackoverflow.com/questions/24428513/double-bitwise-not-in-c-sharp