c++ - Avoiding data race of boolean variables with pthreads -


in code have following structure:

parent thread

somedatatype thread1_continue, thread2_continue; // bool guarantee no data race? 

thread 1:

while (thread1_continue) {   // work } 

thread 2:

while (thread2_continue) {   // work } 

so wonder data type should thread1_continue or thread2_continue avoid data race. , if there data type or technique in pthread solve problem.

there no built-in basic type guarantees thread safety, no matter how small. if working bool or unsigned char, neither reading nor writing guaranteed atomic. in other words: there chance if more threads independantly working same memory, 1 thread can overwrite memory partially while other reads trash value ~ in case behavior undefined.

you use mutex wrap critical section lock , unlock calls ensure mutual exclusion - there 1 thread able execute code. more sophisticated synchronization there semaphores, condition variables or patterns / idioms describing how synchronization can handled using these (light switch, turniket, etc.). study more these, simple examples can found here :)

note there might more complex types / wrappers available wrap way object being accessed - such std::atomic template in c++11, nothing internally handles synchronization don't need explicitly. std::atomic there guarantee that: "if 1 thread writes atomic object while thread reads it, behavior well-defined".


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -