X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Fcore%2Fthread.cpp;h=d2451a0d819187e67f0ea41340720e62ac7f3a4a;hp=a8c80b664ce47aa126e2089dd691abbaff941696;hb=609c9a508cfdc7b42c46c4f21d17639204165a00;hpb=967785734be5c3fc6f75da122c2d93ebbb338271 diff --git a/source/core/thread.cpp b/source/core/thread.cpp index a8c80b6..d2451a0 100644 --- a/source/core/thread.cpp +++ b/source/core/thread.cpp @@ -1,89 +1,56 @@ -#ifdef WIN32 -#include -#else -#include -#include -#endif +#include #include "thread.h" +#include "thread_private.h" -namespace Msp { - -struct Thread::Private -{ -#ifdef WIN32 - HANDLE handle; -#else - pthread_t handle; -#endif - - Private(): handle(0) { } - -#ifdef WIN32 - static DWORD WINAPI main_wrapper(void *t) - { reinterpret_cast(t)->main(); return 0; } -#else - static void *main_wrapper(void *t) - { reinterpret_cast(t)->main(); return 0; } -#endif -}; +using namespace std; +namespace Msp { Thread::Thread(): priv_(new Private), - launched_(false) + state_(PENDING) { } Thread::~Thread() { - if(launched_) - { - kill(); - join(); - } + kill(); + join(); delete priv_; } -/** -Waits for the thread to exit. Calling this from the thread will cause a -deadlock. -*/ void Thread::join() { - if(!launched_) + if(state_>=JOINED) return; -#ifdef WIN32 - WaitForSingleObject(priv_->handle, INFINITE); -#else - pthread_join(priv_->handle, 0); -#endif - launched_ = false; + platform_join(); + state_ = JOINED; } -/** -Violently terminates the thread. -*/ void Thread::kill() { -#ifdef WIN32 - TerminateThread(priv_->handle, 0); -#else - pthread_kill(priv_->handle, SIGKILL); -#endif + if(state_!=RUNNING) + return; + + platform_kill(); + state_ = KILLED; } void Thread::launch() { - if(launched_) - return; + if(state_>=RUNNING) + throw logic_error("already launched"); -#ifdef WIN32 - DWORD dummy; // Win9x needs the lpTthreadId parameter - priv_->handle = CreateThread(0, 0, &Private::main_wrapper, this, 0, &dummy); -#else - pthread_create(&priv_->handle, 0, &Private::main_wrapper, this); -#endif - launched_ = true; + platform_launch(); + state_ = RUNNING; +} + +ThreadReturn THREAD_CALL Thread::Private::main_wrapper(void *arg) +{ + Thread *thread = reinterpret_cast(arg); + thread->main(); + thread->state_ = FINISHED; + return 0; } } // namespace Msp