Quantcast
Channel: multithreading with std::atomic - Stack Overflow
Viewing all articles
Browse latest Browse all 2

multithreading with std::atomic

$
0
0

In the small code example below, I do not understand that, when a thread start to increase the counter the thread will write the counter address in the cache that is shared between core and make the counter lock in the cache until this thread have finish writing in the counter, but if another try to add +1 to this counter between the previous thread read write modify, he will see that the data in the cache is lock and then what ? will the second thread will sleep or just wait until the counter in the cache become unlock ..?

If the thread sleep I do not see the benefit between atomic and mutex for small size data:

// this_thread::yield example#include <iostream>       // std::cout#include <thread>         // std::thread, std::this_thread::yield#include <atomic>         // std::atomicstd::atomic<bool> ready (false);std::atomic<int> counter (0);void count1m(int id) {  while (!ready) {             // wait until main() sets ready...    std::this_thread::yield();  }  for (volatile int i=0; i<10000; ++i) {        counter +=1;}}int main (){  std::thread threads[10];  std::cout << "race of 10 threads that count to 1 million:\n";  for (int i=0; i<10; ++i) threads[i]=std::thread(count1m,i);  ready = true;               // go!  for (auto& th : threads) th.join();  std::cout << counter;}

Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images