多个线程访问同一资源时,为了保证数据的一致性,最简单的方式就是使用 mutex(互斥锁)。
引用 cppreference 的介绍:
The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.
Mutex 1
直接操作 mutex,即直接调用 mutex 的 lock / unlock 函数。
#include
#include
#include
#include
std::mutex g_mutex;
int g_count = 0;
void Counter() {
g_mutex.lock();
int i = ++g_count;
std::cout << "count: " << i << std::endl;
// 前面代码如有异常,unlock 就调不到了。
g_mutex.unlock();
}
int main() {
const std::size_t SIZE = 4;
// 创建一组线程。
std::vector<:thread> v;
v.reserve(SIZE);
for (std::size_t i = 0; i < SIZE; ++i) {
v.emplace_b