I have this c++ code (VS 2008):
LONGLONG res = InterlockedIncrement64(&m_longlong);
running along it, I would like to be able to read from the same variable
LONGLONG res = InterlockedWHAT?64(&m_longlong)
Since this is a 64-bit variable, a simple read is not considered threadsafe, yet I cannot find the correct InterlockedXXX.
How should I read this variable?
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.
The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. They also perform operations on variables in an atomic manner. The threads of different processes can use these functions if the variable is in shared memory.
It lets you do small and well-defined operations safely in a multi-threaded environment: for instance, if you want two threads to increment the same variable, you can use Interlocked to do it instead of acquiring a heavyweight lock and using the "regular increment".
LONGLONG res = InterlockedCompareExchange64(&m_longlong, 0, 0);
You can use InterlockedOr64
and pass zero as the second parameter. So far as I can tell this does not have a requirement of Vista, presumably as it is implemented with compiler intrinsics.
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