]> git.tdb.fi Git - libs/core.git/blob - source/core/thread.cpp
Drop copyright and license notices from source files
[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 /**
47 Waits for the thread to exit.  Calling this from the thread will cause a
48 deadlock.
49 */
50 void Thread::join()
51 {
52         if(!launched_)
53                 return;
54
55 #ifdef WIN32
56         WaitForSingleObject(priv_->handle, INFINITE);
57 #else
58         pthread_join(priv_->handle, 0);
59 #endif
60         launched_ = false;
61 }
62
63 /**
64 Violently terminates the thread.
65 */
66 void Thread::kill()
67 {
68 #ifdef WIN32
69         TerminateThread(priv_->handle, 0);
70 #else
71         pthread_kill(priv_->handle, SIGKILL);
72 #endif
73 }
74
75 void Thread::launch()
76 {
77         if(launched_)
78                 return;
79
80 #ifdef WIN32
81         DWORD dummy;  // Win9x needs the lpTthreadId parameter
82         priv_->handle = CreateThread(0, 0, &Private::main_wrapper, this, 0, &dummy);
83 #else
84         pthread_create(&priv_->handle, 0, &Private::main_wrapper, this);
85 #endif
86         launched_ = true;
87 }
88
89 } // namespace Msp