【问题标题】:How to start several threads in C++?如何在 C++ 中启动多个线程?
【发布时间】: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


【解决方案1】:

在此声明中:

thread t1(thread(thread(tasks[0], parts[0])));

您不需要将一个线程移动到另一个线程,然后再将其移动到另一个线程。只需将您的任务参数直接传递给t1 的构造函数即可:

thread t1(tasks[0], parts[0]);

t2t3t4 相同。


至于你的循环:

for(size_t i=0; i < threads.size(); i++) {
    threads.push_back(thread(tasks[i], parts[i]));
}

假设您使用的是std::vector&lt;std::thread&gt; threads,那么您的循环填充threads 是错误的。充其量,如果threads 最初为空,则循环根本不会做任何事情,因为i &lt; threads.size() 将在size()==0 时为假。在最坏的情况下,如果threads 最初不是空的,那么循环将运行并在每次调用threads.push_back() 时不断增加threads.size(),从而导致无限循环,因为i &lt; threads.size() 永远不会为假,从而将越来越多的线程推入threads 直到内存爆炸。

尝试类似的方法:

size_t numThreads = ...; // taken from cmd line...
std::vector<std::thread> threads(numThreads);

for(size_t i = 0; i < numThreads; i++) {
    threads[i] = std::thread(tasks[i], parts[i]);
}
for(auto &t : threads) {
    t.join();
}

或者这个:

size_t numThreads = ...; // taken from cmd line...
std::vector<std::thread> threads;
threads.reserve(numThreads);

for(size_t i = 0; i < numThreads; i++) {
    threads.emplace_back(tasks[i], parts[i]);
}
for(auto &t : threads) {
    t.join();
}

【讨论】:

  • 您的第一个建议效果很好。非常感谢!
【解决方案2】:

线程不可复制;试试这个:

threads.emplace_back(std::thread(task));

Emplace back thread on vector

【讨论】:

    猜你喜欢
    • 2010-11-22
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 2023-02-11
    • 2013-07-03
    • 2019-01-03
    • 2010-09-08
    相关资源
    最近更新 更多