You compare apples to oranges, as I am sure you expected. The java version is the true CAS with an attempt to retry on failure, and the C version uses what I would call in the form of java a synchronized .
See this question for more details.
See this answer to this question for storytelling support, where it says A full memory barrier is created when this function is invoked , that is, in java terms, this is a synchronized call.
Try using _compare_and_swap in the same way AtomicLong uses its java equivalent, i.e. twists the function until the value changes to what you want.
Added:
I cannot find the final C ++ equivalent of java AtomicLong , but that does not mean that it is not. Essentially, AtomicLong can be changed by any thread at any time, and only one of them will be successful. However, the change will be consistent, i.e. Change will be the result of a change in one stream or another, it will not be a combination of the two. If thread A tries to change the value to 0xffff0000 (or an equivalent 64-bit number), while thread B tries to change the value 0x0000ffff (the same), the result will be either two values, more specifically it will not be 0x00000000 or 0xffffffff (if , of course, the third stream is not involved).
Essentially, AtomicLong has no synchronization whatsoever besides this.
Oldcurmudgeon
source share