mutex
的意思是互斥量, 主要作用是给敏感的数据和代码
进行加锁和去锁
, 让多线程互斥, 防止起冲突.
Header with facilities that allow mutual exclusion (mutex) of concurrent execution of critical sections of code, allowing to explicitly avoid data races.
It contains mutex types
, lock types
and specific functions
:
Mutex types
are lockable types used to protect access to a critical section of code: locking a mutex prevents other threads from locking it (exclusive access) until it is unlocked: mutex, recursive_mutex, timed_mutex, recursive_timed_mutex.Locks
are objects that manage a mutex by associating its access to their own lifetime: lock_guard, unique_lock.Functions
: to lock mutiple mutexes simultaneously (try_lock, lock) and to directly prevent concurrent execution of a specific function (call_once).
mutex: lock(), unlock()
// mutex example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
std::mutex mtx; // mutex for critical section
void print_block(int n, char c) {
// critical section (exclusive access to std::cout signaled by locking mtx):
//mtx.lock();
for