multithreading - C++ : std::atomic<bool> and volatile bool -


i'm reading c++ concurrency in action book anthony williams. , there classic example 2 threads, 1 produce data, other 1 consumes data , a.w. wrote code pretty clear :

std::vector<int> data std::atomic<bool> data_ready(false)  void reader_thread() {     while(!data_ready.load())     {         std::this_thread::sleep(std::milliseconds(1));     }     std::cout << "the answer=" << data[0] << "\n"; }  void writer_thread() {     data.push_back(42);     data_ready = true; } 

and don't understand why code differs 1 i'd use classic volatile bool instead of atomic one. if open mind on subject, i'd grateful. thanks.

the big difference code correct, while version bool instead of atomic<bool> has undefined behavior.

these 2 lines of code create race condition (formally, conflict) because read , write same variable:

reader

while (!data_ready) 

and writer

data_ready = true; 

and race condition on normal variable causes undefined behavior, according c++11 memory model.

the rules found in section 1.10 of standard, relevant being:

two actions potentially concurrent if

  • they performed different threads, or
  • they unsequenced, , @ least 1 performed signal handler.

the execution of program contains data race if contains 2 potentially concurrent conflicting actions, @ least 1 of not atomic, , neither happens before other, except special case signal handlers described below. such data race results in undefined behavior.

you can see whether variable atomic<bool> makes big difference rule.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -