78 lines
1.1 KiB
C++
78 lines
1.1 KiB
C++
|
#include "thread.h"
|
||
|
|
||
|
#define THREAD_STACKSIZE 65536
|
||
|
|
||
|
#define THREAD_READY 0x01
|
||
|
#define THREAD_RUNNING 0x02
|
||
|
#define THREAD_ENDED 0x03
|
||
|
|
||
|
|
||
|
Thread::Thread()
|
||
|
: arg(0), tid(0), state(THREAD_READY)
|
||
|
{}
|
||
|
|
||
|
Thread::~Thread()
|
||
|
{
|
||
|
switch (state) {
|
||
|
case THREAD_RUNNING:
|
||
|
cancel();
|
||
|
|
||
|
case THREAD_ENDED:
|
||
|
join();
|
||
|
|
||
|
case THREAD_READY:
|
||
|
break;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
int Thread::start(void* arg_)
|
||
|
{
|
||
|
pthread_attr_t attr;
|
||
|
|
||
|
if (state != THREAD_READY)
|
||
|
return -1;
|
||
|
|
||
|
arg = arg_;
|
||
|
state = THREAD_RUNNING;
|
||
|
|
||
|
pthread_attr_init(&attr);
|
||
|
pthread_attr_setstacksize(&attr, THREAD_STACKSIZE);
|
||
|
|
||
|
if (pthread_create(&tid, &attr, (Thread::entry), this) != 0) {
|
||
|
state = THREAD_READY;
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
void Thread::cancel()
|
||
|
{
|
||
|
pthread_cancel(tid);
|
||
|
state = THREAD_ENDED;
|
||
|
}
|
||
|
|
||
|
bool Thread::isRunning() const
|
||
|
{
|
||
|
return (state == THREAD_RUNNING);
|
||
|
}
|
||
|
|
||
|
int Thread::join()
|
||
|
{
|
||
|
void* retval;
|
||
|
pthread_join(tid, &retval);
|
||
|
state = THREAD_READY;
|
||
|
|
||
|
return (int)retval;
|
||
|
}
|
||
|
|
||
|
void* Thread::entry(void* myself)
|
||
|
{
|
||
|
Thread* thread = (Thread*)myself;
|
||
|
|
||
|
int retval = thread->execute(thread->arg);
|
||
|
thread->state = THREAD_ENDED;
|
||
|
|
||
|
return (void*)retval;
|
||
|
}
|