写一个线程锁的完整调用例子
时间: 2024-04-14 17:29:55 浏览: 15
当创建并启动多个线程访问共享资源时,使用互斥锁可以确保线程之间的互斥访问。以下是一个完整的使用线程锁的例子:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 定义互斥锁
int sharedData = 0; // 共享资源
// 线程函数,用于递增共享资源的值
void incrementData() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard<std::mutex> lock(mtx); // 锁住互斥锁
sharedData++; // 对共享资源进行操作
}
}
int main() {
std::thread t1(incrementData);
std::thread t2(incrementData);
t1.join();
t2.join();
std::cout << "Shared data: " << sharedData << std::endl;
return 0;
}
```
在上述示例中,我们创建了一个互斥锁`mtx`和一个共享资源`sharedData`。`incrementData`函数用于递增`sharedData`的值,它会通过互斥锁确保每个线程在访问共享资源时是互斥的。在主函数中,我们创建了两个线程`t1`和`t2`,并启动它们来同时递增`sharedData`的值。最后,我们输出最终的共享数据值。
通过使用互斥锁,我们可以确保在每个线程访问共享资源时,只有一个线程能够持有互斥锁并执行操作,从而避免了数据竞争和不一致的结果。