Windows C++多线程编程:Mutex的应用
在多线程编程中,为了保证共享资源的并发访问的正确性,我们需要使用互斥量(mutex)来进行同步。互斥量是一种同步机制,确保同一时间只有一个线程能访问共享资源。
以下是使用互斥量实现线程同步的示例代码:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx; // 定义互斥量
void print(int num)
{
for (int i = 0; i < 5; i++)
{
mtx.lock(); // 上锁
cout << "线程" << num << ": " << i << endl;
mtx.unlock(); // 解锁
}
}
int main()
{
thread t1(print, 1);
thread t2(print, 2);
t1.join();
t2.join();
return 0;
}
在上述代码中,我们通过 mtx.lock()
上锁,确保同一时间只有一个线程可以运行,再通过