gpt4 book ai didi

c++ - 创建可变数量的 std::threads

转载 作者:行者123 更新时间:2023-11-30 03:46:52 24 4
gpt4 key购买 nike

我有一个线程程序,我必须在多台计算机上运行。他们每个人都有不同数量的支持线程。在我开发程序的计算机中有 4 个线程,所以我硬编码了 4 个线程来创建。我想让这个根据情况而变化。我想使用 std::thread::hardware_concurrency 获取线程数,并将工作划分为可用线程数。这可能吗 ?

硬编码的线程创建是:

   //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 ,但我是多线程编程的新手,不知道该怎么做。

感谢您的宝贵时间。

最佳答案

Is this possible ?

是的。

I am thinking of using a std::vector

好主意。这正是我建议您使用的。 vector 中的线程数在运行时可能会有所不同。

but I am new to multi threaded programming and don't know how do it.

您只能在创建其他线程的原始主线程中使用线程 vector 。由于您在单线程中使用 vector ,因此它的使用与在单线程程序中使用 vector 没有任何区别。

关于c++ - 创建可变数量的 std::threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33941508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com