c++ - Real world example of noticeable unsafe behavior of multithreaded code with volatile -


i've read multiple answers , articles stating why volatile doesn't make multithreaded c++ code safe.

i understand reasoning, think understand possible dangers, issue can't create or find example code or mention of situation program using synchronization produces visible wrong or unexpected behavior. don't need reproducible (as current compilers optimizations seem try producing safe code), example happened.

say have counter want use keep track of how many times operation completed, incrementing counter each time.

if run operation in multiple threads unless counter std::atomic or protected lock unexpected results, volatile not help.

here simplified example reproduces unpredictable results, @ least me:

#include <future> #include <iostream> #include <atomic>  volatile int counter{0}; //std::atomic<int> counter{0};  int main() {     auto task = []{                        for(int = 0; != 1'000'000; ++i) {                           // operation...                           ++counter;                       }                   };     auto future1 = std::async(std::launch::async, task);     auto future2 = std::async(std::launch::async, task);     future1.get();     future2.get();     std::cout << counter << "\n"; } 

live demo.

here starting 2 tasks using std::async using std::launch::async launch policy force launch asynchronously. each task increments counter million times. after 2 tasks complete expect counter 2 million.

however, increment read , write operation between reading counter , writing thread may have written , increments may lost. in theory, because have entered realm of undefined behaviour, absolutely happen!

if change counter std::atomic<int> behaviour expect.

also, thread using counter detect if operation has been completed. unfortunately, there nothing stopping compiler reordering code , incrementing counter before has done operation. again, solved using std::atomic<int> or setting necessary memory fences.

see effective modern c++ scott meyers more information.


Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -