我有一个方法testA会被多次调用,每次执行100次1+1的操作,然后我需要把这100次执行1+1的操作分给3个线程,c++代码应该怎么写
时间: 2024-03-19 13:46:26 浏览: 18
可以使用C++11提供的std::thread库中的多线程功能来实现这个需求,以下是一个示例代码:
```c++
#include <iostream>
#include <thread>
#include <vector>
void testA(int start, int end)
{
for(int i = start; i < end; i++)
{
int result = 1 + 1;
std::cout << "Thread " << std::this_thread::get_id() << " : " << result << std::endl;
}
}
int main()
{
int total_count = 100;
int thread_count = 3;
int count_per_thread = total_count / thread_count;
std::vector<std::thread> threads;
for(int i = 0; i < thread_count; i++)
{
int start = i * count_per_thread;
int end = (i == thread_count-1) ? total_count : (start + count_per_thread);
threads.emplace_back(testA, start, end);
}
for(auto& t : threads)
{
t.join();
}
return 0;
}
```
其中,`total_count`表示需要执行的总次数,`thread_count`表示需要开启的线程数量,`count_per_thread`表示每个线程需要执行的次数。通过计算出每个线程需要执行的起始和结束位置,将这些位置作为参数传递给线程,并将线程存储在一个vector中。最后,等待所有线程执行完毕后退出程序。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)