现在我需要用5个线程执行总共100次1+1的c++代码
时间: 2024-03-19 19:45:47 浏览: 23
下面是一个使用 5 个线程执行 100 次 1+1 的 C++ 代码示例:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 定义一个互斥锁
void operation(int id) {
for (int i = 0; i < 20; ++i) {
mtx.lock(); // 加锁,防止多个线程同时操作 count
std::cout << "Thread " << id << " executing operation " << i << std::endl;
int count = 1 + 1;
std::cout << "Thread " << id << " count = " << count << std::endl;
mtx.unlock(); // 解锁
}
}
int main() {
std::thread threads[5];
// 创建 5 个线程并让它们执行操作
for (int i = 0; i < 5; ++i) {
threads[i] = std::thread(operation, i);
}
// 等待所有线程执行完毕
for (int i = 0; i < 5; ++i) {
threads[i].join();
}
return 0;
}
```
在上面的代码中,我们定义了一个名为 `operation` 的函数,它接受一个整数参数 `id`,表示当前线程的 ID。在 `operation` 函数中,我们使用一个简单的循环来模拟操作的执行,其中我们使用了一个互斥锁 `mtx` 来保护 `count` 变量的访问。在主函数中,我们创建了 5 个线程,并让它们执行 `operation` 函数。最后,我们使用 `join` 函数等待所有线程执行完毕。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)