Advertisement
aircampro

std::atomic usage

Jan 20th, 2023
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | Source Code | 0 0
  1. // ref:- https://hiroyukichishiro.com/atomic-in-c-language/
  2. // Example code of demonstrating threads with std::atomics
  3. //
  4. #include <iostream>
  5. #include <atomic>
  6. #include <thread>
  7. int data = 0;
  8. volatile std::atomic<bool> ready(false);
  9.  
  10. // The function will print when it is sure the main thread set the trigger value to true
  11. //
  12. void f()
  13. {
  14.   while (!ready.load(std::memory_order_relaxed)) {
  15.   }
  16.   std::atomic_thread_fence(std::memory_order_acquire);
  17.   std::cout << data << std::endl;
  18. }
  19.  
  20. // this function will set the value and feedback to the master to print it once done
  21. //
  22. void y()
  23. {
  24.   while (!ready.load(std::memory_order_relaxed)) {
  25.   }
  26.   std::atomic_thread_fence(std::memory_order_acquire);
  27.   std::cout << "\033[32m inside thread == " << data << "\033[0m" << std::endl;
  28.   data = 99;
  29.   std::atomic_thread_fence(std::memory_order_release);
  30.   ready.store(false, std::memory_order_relaxed);
  31. }
  32.  
  33. int main()
  34. {
  35.   //
  36.   // In this one we wait for the for loop to be complete
  37.   //
  38.   std::thread t(f);
  39.   data = 3;
  40.   std::atomic_thread_fence(std::memory_order_release);
  41.  
  42.   for (int ii=0; ii<=1000000; ++ii) {
  43.     data = ii;
  44.   }
  45.   ready.store(true, std::memory_order_relaxed);
  46.   t.join();
  47.  
  48.   //
  49.   // In this one we dont wait for the for loop to be complete
  50.   //
  51.   std::thread x(f);
  52.   data = 3;
  53.   std::atomic_thread_fence(std::memory_order_release);
  54.   ready.store(true, std::memory_order_relaxed);
  55.   for (int ii=0; ii<=1000000; ++ii) {
  56.     data = ii;
  57.   }
  58.   x.join();
  59.  
  60.   //
  61.   // here we are waiting for the thread to set the atomic to a value and release it
  62.   //
  63.   std::thread z(y);
  64.   std::atomic_thread_fence(std::memory_order_release);
  65.   data = 3;
  66.   ready.store(true, std::memory_order_relaxed);
  67.   while (ready.load(std::memory_order_relaxed)) {
  68.   }
  69.   std::atomic_thread_fence(std::memory_order_acquire);
  70.   std::cout << data << std::endl;
  71.   z.join();
  72.  
  73.   //
  74.   // here we dont care about the thread before we print the atomic value
  75.   //
  76.   std::thread zz(y);
  77.   std::atomic_thread_fence(std::memory_order_release);
  78.   ready.store(true, std::memory_order_relaxed);
  79.   data = 3;
  80.   std::cout << data << std::endl;
  81.   data = 6;
  82.   zz.join();
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement