Boost:创建一组线程并等待所有线程的正确习惯用法是什么

Boost: What is the proper idiom to create a group of threads and wait for them all?

本文关键字:线程 是什么 惯用法 习惯 等待 创建 一组 Boost      更新时间:2023-10-16

我想使用Boost创建n个线程,每个线程在一个对象上调用一个方法,然后使用join_all等待它们全部完成。我希望使用thread_groupjoin_all会很简单,但我对以下内容感到困惑:

  1. 虽然thread允许传递对象和方法,但thread_group::create_thread不允许。这是可以解决的(如如何将函数参数传递给boost::thread_groups::create_thread()),但我不确定这种差异是否有原因;如果有的话,我想知道在我深入研究之前的理由是什么。

  2. 我不确定线程和我传递的对象的作用域和生存期。我的理解是,对于简单的线程,thread和传递的对象都可以毫无问题地超出作用域:实际的系统线程保持运行,并且传递的对象被复制。但是,在这里,thread_group似乎会使这一点复杂化,尤其是如果我需要使用new(根据上面提到的解决方法)。

  3. 最后,如果我真的使用new,谁会使用delete?我试图弄清楚如何使用智能指针,但删除似乎发生在for循环中,在join_all之前呼叫

到目前为止,我的代码是:

for (int i = 0; i < numThreads; i++) {
W w = W(...);
//threadGroup.create_thread(&W::work, &w); // Won't work, create_thread won't take params
boost::thread(&W::task, w);
}

使用带绑定的线程组。

下面,w将通过值绑定到绑定表达式中(因此它被复制)。请参阅例如boost::bind()是否按引用或值复制?

如果您的员工不可复制而不是new方法,请考虑

  • 使用移动:bind(&W::work, std::move(w))或仅bind(&W::work, W("some", 42, "args"))
  • 使用sharedptr(boost-bind将知道如何调用其上的成员函数

Coliru

#include <boost/thread.hpp>
static const int numThreads = 10;
struct W {
W(...) {}
void work() {
}
};
int main()
{
boost::thread_group tg;
for (int i = 0; i < numThreads; i++) {
W w = W("some", 42, "args");
tg.create_thread(boost::bind(&W::work, &w));
}
tg.join_all();
}