Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // example of thread and atomic
- // g++ prog.cc -Wall -Wextra -I/opt/wandbox/boost-1.73.0/gcc-head/include -std=gnu++2b
- //
- #include <iostream>
- #include <cstdlib>
- #include <string>
- #include <thread>
- #include <atomic>
- std::atomic_int integer{0};
- std::atomic_bool flagA{false};
- std::atomic_bool flagB{false};
- void thread1()
- {
- flagB.store(true, std::memory_order_release); // set memory
- if(flagA.load(std::memory_order_acquire)) // check other memory
- ++g_integer; // set global intger
- }
- void thread2()
- {
- flagA.store(true, std::memory_order_release);
- if(flagB.load(std::memory_order_acquire))
- ++g_integer;
- }
- void thread3()
- {
- flagA.store(false, std::memory_order_release);
- if(flagB.load(std::memory_order_acquire))
- --g_integer;
- }
- int main()
- {
- ++integer;
- flagA.store(true, std::memory_order_release);
- std::thread firstThread(&thread1);
- std::thread secondThread(&thread2);
- firstThread.join();
- secondThread.join();
- std::cout << g_integer << " " << flagA.load(std::memory_order_acquire) << " " << flagB.load(std::memory_order_acquire) << std::endl;
- std::thread firstThread1(&thread3);
- std::thread secondThread1(&thread1);
- firstThread1.join();
- secondThread1.join();
- std::cout << g_integer << " " << flagA.load(std::memory_order_acquire) << " " << flagB.load(std::memory_order_acquire) << std::endl;
- std::thread firstThread2(&thread2);
- std::thread secondThread2(&thread1);
- firstThread2.join();
- secondThread2.join();
- std::cout << g_integer << " " << flagA.load(std::memory_order_acquire) << " " << flagB.load(std::memory_order_acquire) << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement