I am reading the book of CPP-Concurrency-In-Action-2ed-2019. In chapter 5.3, the author gives a simple example:
#include <vector>
#include <atomic>
#include <iostream>
std::vector<int> data;
std::atomic<bool> data_ready(false);
void reader_thread()
{
while(!data_ready.load()) // 1
{
std::this_thread::sleep(std::milliseconds(1));
}
std::cout<<"The answer="<<data[0]<<"\m"; // 2
}
void writer_thread()
{
data.push_back(42); // 3
data_ready=true; // 4
}
Althought the author only wants to explain how to use atomic_bool
to control code sequences(i.e syncronization) between threads.But what confuses me is that if I use plain bool
instead of atomic_bool
, isn't it still thread-safe?
#include <vector>
#include <atomic>
#include <iostream>
std::vector<int> data;
bool data_ready(false);
void reader_thread()
{
while(!data_ready) // 1
{
std::this_thread::sleep(std::milliseconds(1));
}
std::cout<<"The answer="<<data[0]<<"\m"; // 2
}
void writer_thread()
{
data.push_back(42); // 3
data_ready=true; // 4
}
Such as +=, -=, *=, |= are not thread-safe, I know that, but only write/read on a POD variable isn't originally thread-safe itself, such as data_ready=true
?
I also search for other answers like Difference between atomic and int, but to be honest, I don't get their point~~