メンバーメソッドの1つのスレッドインスタンスを開始するクラスを作成しようとしています。 私がメインで行います。その後、std :: thread、 `this 'のスレッドを開始する(クラス自体の中から)
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;
}
することは、私は次のエラーを取得する:
[email protected]:~$ g++ -std=c++0x test.cpp In file included from /usr/include/c++/4.6/thread:39:0, from test.cpp:3: /usr/include/c++/4.6/functional: In member function 'void std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__call(std::tuple<_Args ...>&&, std::_Index_tuple<_Indexes ...>, typename std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__enable_if_void<_Res>::type) [with _Res = void, _Args = {}, int ..._Indexes = {}, _Result = void, _Functor = test*, _Bound_args = {}, typename std::_Bind_result<_Result, _Functor(_Bound_args ...)>::__enable_if_void<_Res>::type = int]': /usr/include/c++/4.6/functional:1378:24: instantiated from 'std::_Bind_result<_Result, _Functor(_Bound_args ...)>::result_type std::_Bind_result<_Result, _Functor(_Bound_args ...)>::operator()(_Args&& ...) [with _Args = {}, _Result = void, _Functor = test*, _Bound_args = {}, std::_Bind_result<_Result, _Functor(_Bound_args ...)>::result_type = void]' /usr/include/c++/4.6/thread:117:13: instantiated from 'void std::thread::_Impl<_Callable>::_M_run() [with _Callable = std::_Bind_result]' test.cpp:28:1: instantiated from here /usr/include/c++/4.6/functional:1287:4: error: '((std::_Bind_result*)this)->std::_Bind_result::_M_f' cannot be used as a function
だから私の推測では、それがこのように動作しないことです。 私の質問は今です:どのように私は、std :: threadを使って、クラスが独自のメソッドの1つのスレッドを開始させることができますか?
'* this'を使用してください。 –
ああ、ヨアキム・ピレボリが答えを出しました! 私が行う場合 pt = new std :: thread(* this); またはさらに pt =新しいstd :: thread(std :: ref(* this)); コンパイルして実行します! –
@FolkertvanHeusden私は、同じクラスのオーバーロードされた 'operator()'を使っているときに、クラスのctor内でスレッドを開始するあなたの構成が奇妙であると言わなければなりません。 –