Reputation: 785
How to guarantee data dependence with c++ atomic?
I want to add something into map in muti-thread, I use atomic_uint64_t for indicator. In every add step,the indicator++.
atomic_uint64_t id;
id.fetch_add(1,memory_order_relaxed);
map[id] = "something";
How can I guarantee the id in map[id]="something"
is the same as the result of id.fetch_add
.
Upvotes: 2
Views: 85
Reputation: 409176
You can't.
The atomicity of id
doesn't prevent some other thread from increasing the value between your fetch_add
call and map[id]
assignment/insertion.
Use a mutex to protect the whole section instead.
By using a mutex, you also prevent data-races for the map access as well.
Upvotes: 5