Alpha
Alpha

Reputation: 149

how to use c++ atomics

I'm confused about C++ atomic variables. If I have an atomic x that I want to increment in one thread and read in another thread, can I do ++x or do I have to do x.atomic_fetch_add(1). In the reader thread, can I do something like cout << x; or do I have to do cout << x.load().

If I have

int x;
atomic<bool> y;

then in thread one

if (!y)
{
   x = 23;
   y = true;
}

and in thread two

if (y)
{
   cout << x;
   y = false;
}

Is it guaranteed that thread two will see the value of (non atomic) x as 23. If not, if I change the access to y to use load and store, will that make a difference? Is it guaranteed that thread two will see the result of all non atomic operations that come before thread one sets y to true?

Can anyone suggest a book that explains these details clearly.

Upvotes: 1

Views: 686

Answers (1)

Gabriel
Gabriel

Reputation: 3604

To summarize you have two questions to ask yourself with the variable y:

  • Is the operation done properly, when variable is shared among threads?

This have to do with the atomicity of the operation, ie done all in one time. Atomicity provides you this guarantee

  • Once the operation is done, do you want all threads to see the same order of operations? Quoting Anthony Williams in C++ Concurrency in Action

Even if the threads are running the same bit of code, they can disagree on the order of events because of operations in other threads in the absence of specific ordering constraints, because the different CPU caches and internal buffers can hold different values for the same memory

This has to do with memory order

As explained in the comments, the operations you do have sufficient level of memory order to guarantee what you would need.

For example assigment sequential consistency is memory_order_seq_cst, see link link here

Hope that helps

Upvotes: 1

Related Questions