Advertisement
aircampro

atomic and thread example

Jun 17th, 2021
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. // example of thread and atomic
  2. // g++ prog.cc -Wall -Wextra -I/opt/wandbox/boost-1.73.0/gcc-head/include -std=gnu++2b
  3. //
  4. #include <iostream>
  5. #include <cstdlib>
  6. #include <string>
  7. #include <thread>
  8. #include <atomic>
  9.  
  10. std::atomic_int integer{0};
  11. std::atomic_bool flagA{false};
  12. std::atomic_bool flagB{false};
  13.  
  14. void thread1()
  15. {
  16.     flagB.store(true, std::memory_order_release);                 // set memory
  17.     if(flagA.load(std::memory_order_acquire))                     // check other memory
  18.         ++g_integer;                                                // set global intger
  19. }
  20. void thread2()
  21. {
  22.     flagA.store(true, std::memory_order_release);            
  23.     if(flagB.load(std::memory_order_acquire))                  
  24.         ++g_integer;                                            
  25. }
  26. void thread3()
  27. {
  28.     flagA.store(false, std::memory_order_release);              
  29.     if(flagB.load(std::memory_order_acquire))                  
  30.         --g_integer;                                            
  31. }
  32. int main()
  33. {
  34.     ++integer;
  35.     flagA.store(true, std::memory_order_release);
  36.    
  37.     std::thread firstThread(&thread1);
  38.     std::thread secondThread(&thread2);
  39.     firstThread.join();
  40.     secondThread.join();
  41.     std::cout << g_integer << " " << flagA.load(std::memory_order_acquire) << " " << flagB.load(std::memory_order_acquire) << std::endl;
  42.    
  43.     std::thread firstThread1(&thread3);
  44.     std::thread secondThread1(&thread1);    
  45.     firstThread1.join();
  46.     secondThread1.join();
  47.     std::cout << g_integer << " " << flagA.load(std::memory_order_acquire) << " " << flagB.load(std::memory_order_acquire) << std::endl;
  48.    
  49.     std::thread firstThread2(&thread2);
  50.     std::thread secondThread2(&thread1);    
  51.     firstThread2.join();
  52.     secondThread2.join();
  53.     std::cout << g_integer << " " << flagA.load(std::memory_order_acquire) << " " << flagB.load(std::memory_order_acquire) << std::endl;
  54.    
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement