Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interlocked reading a 64-bit variable

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?

like image 627
Leo Avatar asked Oct 17 '11 12:10

Leo


People also ask

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.

What are interlocked functions?

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.

What is interlocked C#?

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".


2 Answers

LONGLONG res = InterlockedCompareExchange64(&m_longlong, 0, 0);
like image 82
Henrik Avatar answered Oct 11 '22 06:10

Henrik


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.

like image 32
David Heffernan Avatar answered Oct 11 '22 07:10

David Heffernan