我正在尝试创建一个类,该类启动其成员方法之一的线程实例。
当我在 main 中执行操作时:
test myinstance;
std::thread mythread(myinstance);
然后事情编译。但使用以下结构:
#include <stdio.h>
#include <unistd.h>
#include <thread>
class test
{
std::thread *pt;
public:
test()
{
pt = new std::thread(this);
}
void operator()() const
{
printf("thread start\n");
sleep(5);
printf("thread end\n");
}
};
int main(int arg, char *argv[])
{
test ptest;
sleep(10);
return 0;
}
我收到以下错误:
Folkert@here:~$ g++ -std=c++0x test.cpp 在包含的文件中
/usr/include/c++/4.6/thread:39:0,
来自 test.cpp:3: /usr/include/c++/4.6/function: 在成员函数 'void std::_Bind_result<_result _functor ...>::__call(std::tuple<_args ...>&&, std::_Index_tuple<_indexes ...>,类型名 std::_Bind_result<_result _functor ...>::__enable_if_void<_res>::type) [其中 _Res = void, _Args = {},
int ..._Indexes = {},_Result = void,_Functor = test*,_Bound_args =
{},类型名 std::_Bind_result<_result _functor ...>::__enable_if_void<_res>::type = int]':
/usr/include/c++/4.6/function:1378:24:实例化自
'std::_Bind_result<_result _functor ...>::result_type
std::_Bind_result<_result _functor ...>::operator()(_Args&& ...) [其中 _Args = {}, _Result = void,
_Functor = test*, _Bound_args = {}, std::_Bind_result<_result _functor ...>::result_type = void]' /usr/include/c++/4.6/thread:117:13: 从 ' 实例化空白
std::thread::_Impl<_callable>::_M_run() [with _Callable =
std::_Bind_result]' test.cpp:28:1:实例化自
这里 /usr/include/c++/4.6/functioning:1287:4: 错误:
'((std::_Bind_result*)this)->std::_Bind_result::_M_f' 不能用作函数
所以我的猜测是它不会起作用this way。
我现在的问题是:如何使用 std::thread 让一个类启动它自己的方法之一的线程?
One of std::thread
s 构造函数如下所示:
template<typename Callable>
explicit thread(Callable func);
这需要你传递一些东西callable,这意味着它可以被调用operator()
。你要传递给你的std::thread
不可调用。
你不能打电话this
. this
是指向当前对象的指针,它不可调用。
您需要将成员函数或其他函数传递到您的std::thread
构造函数。
您还可以创建一个函子并传递它,因为它是可调用的。
编辑:刚刚注意到确实超载了operator()
,要调用它,您必须执行以下操作:
test t;
std::thread my_thread(t); //invokes operator() on test.
//also remove this statement from your ctor: pt = new std::thread(this);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)