1
/* $Id: thread_pthread.cpp 15663 2009-03-10 11:12:03Z rubidium $ */
3
/** @file thread_pthread.cpp POSIX pthread implementation of Threads. */
10
* POSIX pthread version for ThreadObject.
12
class ThreadObject_pthread : public ThreadObject {
14
pthread_t thread; ///< System thread identifier.
15
OTTDThreadFunc proc; ///< External thread procedure.
16
void *param; ///< Parameter for the external thread procedure.
17
bool self_destruct; ///< Free ourselves when done?
21
* Create a pthread and start it, calling proc(param).
23
ThreadObject_pthread(OTTDThreadFunc proc, void *param, bool self_destruct) :
27
self_destruct(self_destruct)
29
pthread_create(&this->thread, NULL, &stThreadProc, this);
32
/* virtual */ bool Exit()
34
assert(pthread_self() == this->thread);
35
/* For now we terminate by throwing an error, gives much cleaner cleanup */
36
throw OTTDThreadExitSignal();
39
/* virtual */ void Join()
41
/* You cannot join yourself */
42
assert(pthread_self() != this->thread);
43
pthread_join(this->thread, NULL);
48
* On thread creation, this function is called, which calls the real startup
49
* function. This to get back into the correct instance again.
51
static void *stThreadProc(void *thr)
53
((ThreadObject_pthread *)thr)->ThreadProc();
58
* A new thread is created, and this function is called. Call the custom
59
* function of the creator of the thread.
63
/* Call the proc of the creator to continue this thread */
65
this->proc(this->param);
66
} catch (OTTDThreadExitSignal e) {
72
pthread_detach(pthread_self());
78
/* static */ bool ThreadObject::New(OTTDThreadFunc proc, void *param, ThreadObject **thread)
80
ThreadObject *to = new ThreadObject_pthread(proc, param, thread == NULL);
81
if (thread != NULL) *thread = to;
86
* POSIX pthread version of ThreadMutex.
88
class ThreadMutex_pthread : public ThreadMutex {
90
pthread_mutex_t mutex;
95
pthread_mutex_init(&this->mutex, NULL);
98
/* virtual */ ~ThreadMutex_pthread()
100
pthread_mutex_destroy(&this->mutex);
103
/* virtual */ void BeginCritical()
105
pthread_mutex_lock(&this->mutex);
108
/* virtual */ void EndCritical()
110
pthread_mutex_unlock(&this->mutex);
114
/* static */ ThreadMutex *ThreadMutex::New()
116
return new ThreadMutex_pthread();