Boost:创建一组线程并等待所有线程的正确习惯用法是什么
Boost: What is the proper idiom to create a group of threads and wait for them all?
我想使用Boost创建n个线程,每个线程在一个对象上调用一个方法,然后使用join_all
等待它们全部完成。我希望使用thread_group
和join_all
会很简单,但我对以下内容感到困惑:
-
虽然
thread
允许传递对象和方法,但thread_group::create_thread
不允许。这是可以解决的(如如何将函数参数传递给boost::thread_groups::create_thread()),但我不确定这种差异是否有原因;如果有的话,我想知道在我深入研究之前的理由是什么。 -
我不确定线程和我传递的对象的作用域和生存期。我的理解是,对于简单的线程,
thread
和传递的对象都可以毫无问题地超出作用域:实际的系统线程保持运行,并且传递的对象被复制。但是,在这里,thread_group
似乎会使这一点复杂化,尤其是如果我需要使用new
(根据上面提到的解决方法)。 -
最后,如果我真的使用
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();
}
相关文章:
- 线应该是什么意思
- 调用boost.asio的异步函数时,线程是什么时候创建的
- std::async 如果线程是从 DLL 创建的,则会阻止进程退出?
- Qt的事件循环线程是安全的还是原子的?处理"队列连接"时如何同步?
- C++多线程:是本地静态lambda线程安全的初始化
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- C++-这些线程是在for循环完成后销毁的
- 非CS人员需要了解线程是如何工作的,因为它与多核处理器有关
- 在构造函数中使用"this"启动线程是安全的?
- 线x=是什么!你的意思是
- 多线程_MULTI_THREADED什么
- “致命的 Python 错误:PyThreadState_Get:没有当前线程”是什么意思
- 线程是标准C++的一部分
- 通过引用将循环计数器或范围声明传递给线程有什么区别
- 为什么 c++ 线程是可移动的,但不可复制
- Qt::线程是一个库还是仅仅是一个类
- 如果一个程序的主要功能是从磁盘中读取数据,那么让它多线程是不是一个好主意?
- c++ 11线程和Boost线程有什么区别吗?
- 使用所有可用的线程是不好的做法
- 在C++11中,"不代表执行线程"的线程有什么意义?