1
/* $Id: thread_win32.cpp 15159 2009-01-20 03:44:43Z rubidium $ */
3
/** @file thread_win32.cpp Win32 thread implementation of Threads. */
8
#include "core/alloc_func.hpp"
14
* Win32 thread version for ThreadObject.
16
class ThreadObject_Win32 : public ThreadObject {
18
HANDLE thread; ///< System thread identifier.
19
uint id; ///< Thread identifier.
20
OTTDThreadFunc proc; ///< External thread procedure.
21
void *param; ///< Parameter for the external thread procedure.
22
bool self_destruct; ///< Free ourselves when done?
26
* Create a win32 thread and start it, calling proc(param).
28
ThreadObject_Win32(OTTDThreadFunc proc, void *param, bool self_destruct) :
33
self_destruct(self_destruct)
35
this->thread = (HANDLE)_beginthreadex(NULL, 0, &stThreadProc, this, CREATE_SUSPENDED, &this->id);
36
if (this->thread == NULL) return;
37
ResumeThread(this->thread);
40
/* virtual */ ~ThreadObject_Win32()
42
if (this->thread != NULL) {
43
CloseHandle(this->thread);
48
/* virtual */ bool Exit()
50
assert(GetCurrentThreadId() == this->id);
51
/* For now we terminate by throwing an error, gives much cleaner cleanup */
52
throw OTTDThreadExitSignal();
55
/* virtual */ void Join()
57
/* You cannot join yourself */
58
assert(GetCurrentThreadId() != this->id);
59
WaitForSingleObject(this->thread, INFINITE);
64
* On thread creation, this function is called, which calls the real startup
65
* function. This to get back into the correct instance again.
67
static uint CALLBACK stThreadProc(void *thr)
69
((ThreadObject_Win32 *)thr)->ThreadProc();
74
* A new thread is created, and this function is called. Call the custom
75
* function of the creator of the thread.
80
this->proc(this->param);
81
} catch (OTTDThreadExitSignal) {
86
if (self_destruct) delete this;
90
/* static */ bool ThreadObject::New(OTTDThreadFunc proc, void *param, ThreadObject **thread)
92
ThreadObject *to = new ThreadObject_Win32(proc, param, thread == NULL);
93
if (thread != NULL) *thread = to;
98
* Win32 thread version of ThreadMutex.
100
class ThreadMutex_Win32 : public ThreadMutex {
102
CRITICAL_SECTION critical_section;
107
InitializeCriticalSection(&this->critical_section);
110
/* virtual */ ~ThreadMutex_Win32()
112
DeleteCriticalSection(&this->critical_section);
115
/* virtual */ void BeginCritical()
117
EnterCriticalSection(&this->critical_section);
120
/* virtual */ void EndCritical()
122
LeaveCriticalSection(&this->critical_section);
126
/* static */ ThreadMutex *ThreadMutex::New()
128
return new ThreadMutex_Win32();