c++ - 无法使用 packaged_task 在 thread_group 中创建线程

标签 c++ multithreading boost

我想创建一组线程,它们都有 future (这就是我使用 packaged_tasks 的原因),这样我就可以使用它们返回的值。 但是,以下代码在编译期间返回错误:

boost::thread_group group;


for(int i=0; i<4; i++){
    boost::packaged_task<int> task(std::bind(&matchThis,someStr, anotherStr));
    boost::unique_future<int> fi=task.get_future();

    //add task to task-group
    group.create_thread(boost::move(task));
    group.join_all();
}

这是错误:

c:\boost\boost\thread\detail\thread_group.hpp:42: ERROR: "boost::packaged_task::packaged_task": No access to private member which was declared in the boost::packaged_task-class . with [ R=int] ...

当我创建这样一个线程时,这段代码工作得很好:

boost::thread thread(boost::move(task));

那么改用 thread_groups 有什么问题呢?

最佳答案

我假设您没有使用 C++11(因为我认为如果您使用的话它会起作用。)

boost::thread 已“启用移动”,因此它可以接受 boost::move 返回的模拟右值引用。 boost::thread_group 还没有以同样的方式“启用移动”,因此 create_thread 的参数必须是可复制的,并且 packaged_task不可复制。

我会建议检查 Boost Trac 错误数据库,如果没有已经添加 create_thread 请求以支持移动的右值。

关于c++ - 无法使用 packaged_task 在 thread_group 中创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10905132/

相关文章:

c++ - 理解 C++ 字符串

c++ - Dev-C++ 在没有 GUI 的情况下在后台运行程序

c++ - 与 boost::asio 一起使用的 std::string 的替代品

c++ - 使用notify all进行多次等待

c# - .NET - 线程同步

c++ - 通过 boost::asio::udp 以高数据速率发送图像数据?

c++ - 为 Boost 日志对象重载 << 运算符

c++ - 我对转换运算符的继承感到困惑

c++ - 基于共享内存的原子变量如何在进程间上下文中工作?

c++ - 如何从 boost::ptr_vector 中删除 "this"