X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Fcore%2Fthread.cpp;h=cfc0c37573d02a100df148a433a0bf365b76111f;hp=a0d21875241e584614da7ed01aef0dd4ae4ae325;hb=8db2c378e1d006afb792d829857e866541bf81a5;hpb=cfc8e0b7b15ea505bd6a6a9599cbc5ce1e316963 diff --git a/source/core/thread.cpp b/source/core/thread.cpp index a0d2187..cfc0c37 100644 --- a/source/core/thread.cpp +++ b/source/core/thread.cpp @@ -1,60 +1,68 @@ -/* $Id$ - -This file is part of libmspcore -Copyright © 2006 Mikko Rasa, Mikkosoft Productions -Distributed under the LGPL -*/ - -#ifndef WIN32 +#ifdef WIN32 +#include +#else +#include #include #endif #include "thread.h" namespace Msp { -/** -Waits for the thread to exit. Calling this from the thread will cause a -deadlock. -*/ -void Thread::join() +struct Thread::Private { - if(!launched_) - return; +#ifdef WIN32 + HANDLE handle; +#else + pthread_t handle; +#endif + + Private(): handle(0) { } #ifdef WIN32 - WaitForSingleObject(thread_, INFINITE); + static DWORD WINAPI main_wrapper(void *t) + { reinterpret_cast(t)->main(); return 0; } #else - pthread_join(thread_, 0); + static void *main_wrapper(void *t) + { reinterpret_cast(t)->main(); return 0; } #endif - launched_=false; -} +}; -/** -Requests the thread to terminate gracefully. Currently unimplemented on win32. -*/ -void Thread::cancel() + +Thread::Thread(): + priv_(new Private), + launched_(false) +{ } + +Thread::~Thread() { -#ifndef WIN32 //XXX - pthread_cancel(thread_); -#endif + if(launched_) + { + kill(); + join(); + } + delete priv_; } -/** -Violently terminates the thread. -*/ -void Thread::kill() +void Thread::join() { + if(!launched_) + return; + #ifdef WIN32 - TerminateThread(thread_, 0); + WaitForSingleObject(priv_->handle, INFINITE); #else - pthread_kill(thread_, SIGKILL); + pthread_join(priv_->handle, 0); #endif + launched_ = false; } -Thread::~Thread() +void Thread::kill() { - if(launched_) - kill(); +#ifdef WIN32 + TerminateThread(priv_->handle, 0); +#else + pthread_kill(priv_->handle, SIGKILL); +#endif } void Thread::launch() @@ -64,11 +72,11 @@ void Thread::launch() #ifdef WIN32 DWORD dummy; // Win9x needs the lpTthreadId parameter - thread_=CreateThread(0, 0, &main_, this, 0, &dummy); + priv_->handle = CreateThread(0, 0, &Private::main_wrapper, this, 0, &dummy); #else - pthread_create(&thread_, 0, &main_, this); + pthread_create(&priv_->handle, 0, &Private::main_wrapper, this); #endif - launched_=true; + launched_ = true; } } // namespace Msp