]> git.tdb.fi Git - libs/core.git/blob - source/core/thread.cpp
cfc0c37573d02a100df148a433a0bf365b76111f
[libs/core.git] / source / core / thread.cpp
1 #ifdef WIN32
2 #include <windows.h>
3 #else
4 #include <pthread.h>
5 #include <signal.h>
6 #endif
7 #include "thread.h"
8
9 namespace Msp {
10
11 struct Thread::Private
12 {
13 #ifdef WIN32
14         HANDLE handle;
15 #else
16         pthread_t handle;
17 #endif
18
19         Private(): handle(0) { }
20
21 #ifdef WIN32
22         static DWORD WINAPI main_wrapper(void *t)
23         { reinterpret_cast<Thread *>(t)->main(); return 0; }
24 #else
25         static void *main_wrapper(void *t)
26         { reinterpret_cast<Thread *>(t)->main(); return 0; }
27 #endif
28 };
29
30
31 Thread::Thread():
32         priv_(new Private),
33         launched_(false)
34 { }
35
36 Thread::~Thread()
37 {
38         if(launched_)
39         {
40                 kill();
41                 join();
42         }
43         delete priv_;
44 }
45
46 void Thread::join()
47 {
48         if(!launched_)
49                 return;
50
51 #ifdef WIN32
52         WaitForSingleObject(priv_->handle, INFINITE);
53 #else
54         pthread_join(priv_->handle, 0);
55 #endif
56         launched_ = false;
57 }
58
59 void Thread::kill()
60 {
61 #ifdef WIN32
62         TerminateThread(priv_->handle, 0);
63 #else
64         pthread_kill(priv_->handle, SIGKILL);
65 #endif
66 }
67
68 void Thread::launch()
69 {
70         if(launched_)
71                 return;
72
73 #ifdef WIN32
74         DWORD dummy;  // Win9x needs the lpTthreadId parameter
75         priv_->handle = CreateThread(0, 0, &Private::main_wrapper, this, 0, &dummy);
76 #else
77         pthread_create(&priv_->handle, 0, &Private::main_wrapper, this);
78 #endif
79         launched_ = true;
80 }
81
82 } // namespace Msp