c + +提振,在一类使用thread_group [英] C++ Boost, using thread_group in a class
问题描述
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类。每一类对象,以处理工作创建线程。然而,当我编译这个我得到这个奇怪的消息
I created class c. Each class object creates threads in order to process the work. However I get this weird message when I compile this
:错误C2248:提振:: thread_group :: thread_group:不能访问类中声明私有成员'的boost :: thread_group
: error C2248: 'boost::thread_group::thread_group' : cannot access private member declared in class 'boost::thread_group'
此外,只承担任何递归调用的问题。
Besides, just assume is no recursive calling problems.
推荐答案
的问题是,你的code设置的方式是通过你的对象的副本创建一个新的线程。
The issue is that the way your code is set up is passing a copy of your object to create a new thread.
您所得到的错误,因为升压:: thread_group的拷贝构造函数是私有的,所以你不能复制C类的一个对象。因为默认的拷贝构造函数会尝试所有成员复制无法复制C类的一个对象,它无法复制的boost :: thread_group。因此,编译器错误。
You are getting the error because the copy constructor of boost::thread_group is private, so you cannot copy an object of class c. You cannot copy an object of class c because the default copy constructor tries to copy all members, and it cannot copy boost::thread_group. Thus the compiler error.
经典的解决方案,这将是要么编写自己的拷贝构造函数不尝试复制的boost :: thread_group(如果你真的想每次调用一个唯一的thread_group),或存储的boost :: thread_group的一些指针一种可复制(这将共享组,可能是你想要的)。
The classic solution to this would be to either write your own copy constructor that does not try to copy boost::thread_group(if you actually want one unique thread_group per call) or to store boost::thread_group in a pointer of some kind that can be copied(which would share the group, and is probably what you want).
注意:
它通常是简单的不写你自己的操作符(),只是沿着升压::功能票代替。这与做
It is usually simpler to not write your own operator(), and just pass along boost::functions instead. This would be done with
#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的共享,不管是按值在函数调用不共享过去了。
Note that whatever is in the class c is shared, and whatever is passed by value in the function call is not shared.
这篇关于c + +提振,在一类使用thread_group的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!