【发布时间】:2020-07-31 07:54:37
【问题描述】:
我有一些类对象,想将它们交给几个线程。线程数由命令行给出。
当我按照以下方式编写它时,它可以正常工作:
thread t1(thread(thread(tasks[0], parts[0])));
thread t2(thread(thread(tasks[1], parts[1])));
thread t3(thread(thread(tasks[2], parts[2])));
thread t4(thread(thread(tasks[3], parts[3])));
t1.join();
t2.join();
t3.join();
t4.join();
但正如我所提到的,线程数应该由命令行给出,所以它必须更加动态。我尝试了以下代码,它不起作用,我不知道它有什么问题:
for(size_t i=0; i < threads.size(); i++) {
threads.push_back(thread(tasks[i], parts[i]));
}
for(auto &t : threads) {
t.join();
}
我希望有人知道如何纠正它。
【问题讨论】:
-
“不起作用”对我们没有帮助。您是否收到特定错误?
-
旁注:
thread t1(thread(thread(...似乎有点多余,不是吗?
标签: c++ multithreading