views:

682

answers:

3

I have found lock inc addr but that doesn't keep a copy of the stored value around and even a read immediately after it in the same thread could come after a competing write.

The best solution I have found is a load/inc/cas loop.

+8  A: 

lock xadd is your friend.

Anton Tykhyy
+1  A: 

see atomic_impl.h for more x86/x86_64 atomic primitives and usage.

EffoStaff Effo
A: 

This is even simpler:

asm
  Lock inc dword ptr J;
end;

where J is your integer to be thread-safely incremented.

IanC
what reg does the value that was stored end up in?
BCS
None. It directly modifies the memory address where J resides.I have brute-force tested this with multiple threads, and it works 100%. If I remove the lock, the results fail.
IanC
OK, I already know how to do that. Now how do I get the rest of what I asked for; the value that was stored?
BCS
What language are you writing in?The value is stored in J. This is a thread-safe way of saying J = J +1 or J++
IanC
Perhaps you should state your question more clearly. The answer I posted does "keep a copy around".
IanC
Something with inline ASM. I need to increment a value and then know what value *I* incremented it to, not what value that memory stores once I get around to reading it back from memeory. The exact use case that prompted the (more general) question is that several threads would be incrementing a counter and then doing processing based on the new value. Each value in the range should be handled exactly once. Your answer doesn't provide any way to get the stored value without the risk of competing writes getting in the way.
BCS