:
は、ここで簡単な実装(TESTED NOT)です。基本的なC++の仕組みに関する知識が必要です。
基本的な問題は、関数へのポインターがメンバー関数のポインターと異なることです。これは、メンバ関数が暗黙の最初のパラメータthis
を持つためです。 man
ページから
:
int pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg);
スレッドの入口点はvoid* (*)(void*)
です。あなたの関数Base::action
のタイプはvoid* (Base::*)()
です。その醜い型の宣言のBase::
部分は、this
の型を示します。型の不一致は、コンパイラがあなたのコードを受け入れない理由です。
この問題を解決するには、2つのことを解決する必要があります。メンバー関数へのポインタは、this
をインスタンスにバインドしないため、メンバー関数を使用することはできません。タイプvoid*
の単一のパラメータも必要です。ありがたいことに、解決策は明らかにthis
を自分自身に渡すことであるため、これらの2つの修正は手元にあります。
class Base {
public:
virtual void* action() = 0;
protected:
pthread_t tid;
friend void* do_action(void* arg) {
return static_cast<Base*>(arg)->action();
}
};
class Derived : public Base {
public:
Derived() {
// This should be moved out of the constructor because this
// may (will?) be accessed before the constructor has finished.
// Because action is virtual, you can move this to a new member
// function of Base. This also means tid can be private.
pthread_create(&tid, NULL, &do_action, this);
}
virtual void* action();
};
編集: Woops tid
がprotected
かprivate
であれば、その後、do_action
はfriend
する必要があります。
おそらく、あなたは 'boost :: thread'や' std :: thread'(C++ 11の) – PlasmaHH