昔のgcc3の頃にJavaっぽいC++のスレッドクラス作ったものがあったので、メモも兼ねて投稿します。
boostやPocoが使えない職場で使えると思います。
#include<pthread.h>
#include<stdio.h>
#include<iostream>
using namespace std;
class Runnable{
private:
public:
Runnable(){}
virtual ~Runnable(){}
virtual void run() = 0;
};
class Thread : virtual public Runnable{
private:
Runnable * runnable;
pthread_t threadID;
static void * __run( void * cthis ){
static_cast<Runnable*>(cthis)->run();
return NULL;
}
public:
Thread() : runnable(NULL){
}
Thread( Runnable * runnable ){
this->runnable = runnable;
}
int start(){
Runnable * execRunnable = this;
if( this->runnable != NULL ){
execRunnable = this->runnable;
}
return pthread_create( &threadID , NULL , __run , execRunnable );
}
int join(){
return pthread_join( threadID , NULL );
}
};
class HelloWorldThread : public Thread{
public:
virtual void run(){
cout << "Hello World" << endl;
}
};
int main(){
HelloWorldThread helloWorldThread;
helloWorldThread.start();
sleep(1);
helloWorldThread.join();
return 0;
}
Javaと同じようにインスタンスを作成してからstartしないとだめです。最初はコンストラクタと同時にスレッドが動くようにクラスを作成しましたが、pure virtualエラーが発生するので駄目でした。肝はpthread_createのvoidポインターには何でも渡せるのでクラスを渡して、スレッド実行時にクラスのポインターに戻して、メソッドを実行することです。
このテクニックは、シグナルハンドラーなどvoidのポインターを渡す関数でも使えます。