【问题标题】:C++ Boost, using thread_group in a classC++ Boost,在类中使用 thread_group
【发布时间】:2011-12-16 05:04:30
【问题描述】:
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 类。每个类对象都创建线程以处理工作。但是,当我编译这个时,我收到了这个奇怪的消息

:错误 C2248:“boost::thread_group::thread_group”:无法访问在类“boost::thread_group”中声明的私有成员

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

【问题讨论】:

    标签: c++ multithreading boost


    【解决方案1】:

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

    您收到错误是因为 boost::thread_group 的复制构造函数是私有的,因此您无法复制 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 中的任何内容都是共享的,而函数调用中通过值传递的任何内容都不是共享的。

    【讨论】:

    • 但我必须创建具有成员变量和函数的类对象。所以我不能把线程作为一个函数。有没有像我上面那样创建类对象?
    • @LeeJae 正如我在回答中提到的,您必须将 boost::thread_group 存储在某种指针中。我建议使用 shared_ptr。
    • 非常感谢。我对 boost 库了解不多。无论如何,谢谢
    • @Lee 只是不要忘记在开始使用它之前实际创建线程组。例如, void initPool() { thd = boost::make_shared&lt;boost::thread_group&gt;(); } (注意你需要#include )
    猜你喜欢
    • 2012-04-11
    • 1970-01-01
    • 2013-05-16
    • 2013-10-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多