多线程环境取最大值代码实现
时间: 2023-07-26 18:39:52 浏览: 37
下面是一个使用互斥锁实现在多线程环境下取最大值的代码示例(使用 C++11 标准的 std::mutex):
```c++
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
std::mutex mtx; // 定义互斥锁
void find_max(const std::vector<int>& nums, int& max_num)
{
for (auto num : nums) {
mtx.lock(); // 获取互斥锁
if (num > max_num) {
max_num = num;
}
mtx.unlock(); // 释放互斥锁
}
}
int main()
{
std::vector<int> nums = {2, 5, 8, 1, 9, 4};
int max_num = 0;
// 启动两个线程分别查找最大值
std::thread t1(find_max, std::ref(nums), std::ref(max_num));
std::thread t2(find_max, std::ref(nums), std::ref(max_num));
// 等待两个线程结束
t1.join();
t2.join();
std::cout << "The max number is: " << max_num << std::endl;
return 0;
}
```
在上面的代码中,我们定义了一个互斥锁 `mtx`,然后在查找最大值的函数中先获取互斥锁,然后进行比较和更新最大值,最后再释放互斥锁。这样可以确保在任意时刻只有一个线程能够修改最大值,避免了多线程竞争导致的数据不一致问题。