C++ atomic's are good thing, my question is only how they compose together.
uint64_t lpp = (place_st++ == A-1)? place_st.exchange(0) : place_st.load();
...
atomic<uint64_t> place_st;
...
So, is there any guarantee that these operations will be executed ONLY one by one,like in transactional memory
Atomic operations only promise atomicity (and relative ordering given the right parameters): the inability for other operations on different threads to interfere with their operations. Two operations which are both atomic are still two operations , so stuff can happen in-between them.
No, there won't be any guarantee of that, making the code unsafe (one thread might see a value greater than A
, and an increment might be 'lost' by a place_st.exchange(0)
.
The easiest thing to do here might be to just consider place_st
as "unwrapped", and manually do uint64_t lpp = place_st++ % A
to get the "wrapped" version. Beyond that, to get this sort of behavior you'd basically need compare-and-swap in a loop (see how to implement simple Compare And Swap in C++ for shared counter ), rather than the atomic increment, to get the increment and wrapping to behave atomically. Since you're only operating on a single variable, you can use CAS to emulate the transactional memory approach you were considering.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.