トップ «前の日記(2006-10-02(月)) 最新 次の日記(2006-10-04(水))» 編集

とた日記


2006-10-03(火) 曇一時晴 安静時心拍数 61 [長年日記]

_ Thread Class

スレッドクラスを作ってみました。ダサいけどこんな感じ。

#ifndef THREAD_H
#define THREAD_H
 
#include 
 
class Thread
{
public:
        typedef enum {
                JOINABLE,
                DETACHED
        }DETACHSTATE;
        Thread(); ///< default constructor
        virtual ~Thread(); ///< destructor
        virtual int start(DETACHSTATE detachstate); ///< start method
        virtual int join(); ///< join method
 
protected:
        pthread_t m_threadid;
        virtual int run(); ///< 派生クラスでoverrideする
 
private:
        bool m_join_flag;
        static void *start_routine(void *);
 
};
 
#endif // THREAD_H
#include "Thread.h"
 
Thread::Thread() : m_threadid(0), m_join_flag(true)
{
}
 
Thread::~Thread()
{
}
 
void *Thread::start_routine(void *arg)
{
        if(arg == NULL){
                return NULL;
        }
 
        Thread *p = (Thread *)arg;
        p->run();
        return arg;
}
 
int Thread::start(DETACHSTATE detachstate)
{
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_t pt = pthread_create(&m_threadid, &attr, Thread::start_routine, this);
        if(detachstate == DETACHED){
                pthread_detach(m_threadid);
                m_join_flag = false;
        }
        pthread_attr_destroy(&attr);
        return pt;
}
 
int Thread::join()
{
        pthread_t pt = 0;
        if(m_join_flag){
                pt = pthread_join(m_threadid, NULL);
        }
        return pt;
}
 
int Thread::run()
{
        return 0;
}