1. Atomic variables
C++11 provides an atomic type of STD::ATOMIC<T>, which can be used as a template parameter, using an atomic variable without the need to protect the variable with a mutex, which is more concise.
For example, if you want to make a counter, use the mutex and use the atomic variable in the following sequence:
//using mutexes structcounter{intvalue; Std::mutex Mutex; voidincrement () {Std::lock_guard<std::mutex>Lock(mutex); ++value; } voidDecrement () {Std::lock_guard<std::mutex>Lock(mutex); --value; } int Get() { returnvalue; }};intMain () {return 0;}//using atomic variables#include <atomic>structcounter{std::atomic<int>value; voidincrement () {++value; } voidDecrement () {--value; } int Get() { returnvalue; }};
2, Call_once/once_flag
Monotonic functions are in a multithreaded environment, to ensure that a function is called only once, such as to initialize an object, and this object can only be initialized once, you can use std::call_once to ensure that the function in a multithreaded environment is called only once. When using Std::call_once, a once_flag is required as an entry for the call_once.
as an entry for the call_once. #include<thread>#include<iostream>#include<mutex>Std::once_flag Flag;voiddo_once () {std::call_once (flag, [] () {std::cout<<"called once."<<Std::endl;});}intMain () {Std::thread T1 (do_once); Std::thread T2 (do_once); std::thread t3 (do_once); T1.join (); T2.join (); T3.join (); return 0;}//Output:Called once.
C11 thread Management: Atomic variables & monotone functions