问题描述
我有一个线程程序,必须在多台计算机上运行。它们每个都有不同数量的受支持线程。在我开发程序的计算机中,有4个线程,因此我对要创建的4个线程进行了硬编码。我想使这种情况因情况而异。我想使用std :: thread :: hardware_concurrency来获取线程数,并将工作划分为可用的线程数。这可能吗 ?
I have a threaded program that I have to run on multiple computers. Each of them have a different number of supported threads. In the computer that I developed the program there are 4 threads , and so I hard coded 4 threads to be created. I want to make this vary according to the situation . I want to use std::thread::hardware_concurrency to get the number of threads , and divide the work into the number of threads available . Is this possible ?
创建的硬编码线程是:
//const unsigned int SIZE = std::thread::hardware_concurrency ;
const unsigned int SIZE = 4 ;
void zeroOut(std::vector<obj> vec , int start , int end)
{
// Does an operation on vec from start index to end index
}
int main() {
std::vector<obj_thread> vec ;
// Do some work on vec. Fill it with values.
unsigned int step = vec.size()/SIZE;
std::thread thread1(zeroOut,vec,step,step*2);
std::thread thread2(zeroOut,vec,step*2,step*3);
std::thread thread3(zeroOut,vec,step*3,step*4);
zeroOut(vec, 0 , step);
thread1.join();
thread2.join();
thread3.join();
return 0 ;
}
我正在考虑使用std :: vector,但我是新手多线程编程,不知道怎么做。
I am thinking of using a std::vector , but I am new to multi threaded programming and don't know how do it.
谢谢您的时间。
推荐答案
是。
好主意。这正是我建议您使用的。向量中的线程数量在运行时可能会有所不同。
Good idea. That's exactly what I recommend you to use. The number of threads in a vector can vary during runtime.
您只能在创建其他线程的原始主线程中使用线程向量。由于您在单个线程中使用向量,因此它的使用与在单线程程序中使用向量没有任何区别。
You only use the vector of threads in the original main thread that creates the other threads. Since you use the vector in a single thread, it's use doesn't differ in any way from using a vector in a single-threaded program.
这篇关于创建可变数量的std :: threads的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!