C++ Boost,在类中使用thread_group

标签 c++ multithreading boost

class c
{
public:
    int id;
    boost::thread_group thd;
    c(int id) : id(id) {}
    void operator()()
    {
        thd.create_thread(c(1));
        cout << id << endl;
    }


};

我创建了类 c。每个类对象创建线程以处理工作。但是当我编译这个时我得到了这个奇怪的消息

: error C2248: 'boost::thread_group::thread_group' : 无法访问类 'boost::thread_group' 中声明的私有(private)成员

此外,假设没有递归调用问题。

最佳答案

问题在于您的代码设置方式是传递对象的拷贝以创建新线程。

你得到这个错误是因为 boost::thread_group 的复制构造函数是私有(private)的,所以你不能复制类 c 的对象。您不能复制类 c 的对象,因为默认的复制构造函数会尝试复制所有成员,而它不能复制 boost::thread_group。因此编译器错误。

对此的经典解决方案是编写自己的复制构造函数,不尝试复制 boost::thread_group(如果您实际上希望每次调用一个唯一的 thread_group)或将 boost::thread_group 存储在一些指针中可以复制的那种(这将共享组,并且可能是你想要的)。

注意:

不编写自己的 operator() 并传递 boost::functions 通常更简单。这将完成

#include <boost/thread.hpp>
#include <iostream>
using namespace std;
class c
{
public:
    boost::thread_group thd;

    void myFunc(int id)
    {
        boost::function<void(void)> fun = boost::bind(&c::myFunc,this,1);
        thd.create_thread(fun);
        cout << id << endl;
    }


};

请注意,类 c 中的任何内容都是共享,而在函数调用中按值传递的任何内容都不是共享的。

关于C++ Boost,在类中使用thread_group,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8530014/

相关文章:

c++ - C++中全局变量的使用

c++ - Visual C++ (x64) 中的 SSE2 选项

c++ - 在 C++ 中返回多个值和默认参数

python - python 中并行任务的良好实践

c++ - boost::asio::deadline_timer::async_wait 内部出现段错误

C++函数动态数据类型定义

c++ - 类和互斥量

python - ThreadPoolExecutor在最后一个线程完成之前不启动新线程

c++ - Boost 测试在使用 Clang 4.1 (LLVM 3.1svn) 退出时崩溃

c++ - Boost Asio UDP 服务器设置套接字以监听指定 IP