我是C ++的新手,我需要将类对象的成员函数用作线程函数,并且该对象在应用程序类中使用,并且对象无法共享,因此它是唯一的指针。当我尝试创建线程时,出现编译错误。
我不能照原样复制代码,因此只能创建一个示例代码段。
DerivedType
<-Base3Type
<-{Base2Type
<-Base1Type
-DerivedType
在应用程序类中被声明为私有
class AppClass
{
private:
std::unique_ptr<DerivedType> transport;
public:
}
AppClass::Open()
{
transport= std::make_unique<DerivedType>(client, logger);
std::thread receive(&DerivedType::receive, &transport, flag, 1000);//flag and 100 are arguments to DerivedType::receive function.
}
我收到以下编译错误
/usr/include/c++/5.2.1/functional:634:20: **error: pointer to member type ‘void (Base1Type::Base2Type::Base3Type::DerivedType::)(std::shared_ptr<bool>, const short unsigned int&)’ incompatible with object type ‘std::unique_ptr<Base1Type::Base2Type::Base3Type::DerivedType>’**
{ return ((*__ptr).*_M_pmf)(std::forward<_Args>(__args)...); }
^
/usr/include/c++/5.2.1/functional:634:60: **error: return-statement with a value, in function returning 'void' [-fpermissive]**
{ return ((*__ptr).*_M_pmf)(std::forward<_Args>(__args)...); }
请让我知道如何进行编译和执行而不会崩溃。谢谢。
答案 0 :(得分:1)
您希望将成员函数作为线程体来调用,因此您需要传递指向DerivedType
对象的指针(使用unique_ptr::get
方法,而不是指向unique_ptr
的指针,写
std::thread receive(&DerivedType::receive, transport.get(), flag, 1000);//
^^^^^^^^^^^^^^^
并执行而不会崩溃。
现在,在terminate
方法末尾调用线程的析构函数时,您的代码将被Open
中止,因为您的thread
处于可连接状态。所以你需要选择
join
线程对象上调用receive
,然后在Open
方法中等待(没有意义)detach
对象上的receive
,但是您必须确保transport
对象不会在receive
线程中开始的任务结束之前被销毁。