Added a thread utility class to factor out operations on threads.

This commit is contained in:
Michael Bebenita 2010-09-07 18:05:42 -07:00
parent 9b8d647af3
commit 9b74129a4f
2 changed files with 64 additions and 0 deletions

View File

@ -10,3 +10,46 @@ void sync::yield() {
pthread_yield();
#endif
}
#if defined(__WIN32__)
static DWORD WINAPI
#elif defined(__GNUC__)
static void *
#else
#error "Platform not supported"
#endif
rust_thread_start(void *ptr) {
rust_thread *thread = (rust_thread *) ptr;
thread->run();
thread->thread = 0;
return 0;
}
void
rust_thread::start() {
#if defined(__WIN32__)
thread = CreateThread(NULL, 0, rust_thread_start, this, 0, NULL);
#else
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 1024 * 1024);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&thread, &attr, rust_thread_start, (void *) this);
#endif
}
void
rust_thread::join() {
#if defined(__WIN32__)
WaitForSingleObject(thread, INFINITE);
#else
pthread_join(thread, NULL);
#endif
thread = 0;
}
bool
rust_thread::is_running() {
// TODO: This may be broken because of possible races.
return thread;
}

View File

@ -11,4 +11,25 @@ public:
}
};
/**
* Thread utility class. Derive and implement your own run() method.
*/
class rust_thread {
public:
#if defined(__WIN32__)
HANDLE thread;
#else
pthread_t thread;
#endif
void start();
virtual void run() {
return;
}
void join();
bool is_running();
};
#endif /* SYNC_H */