]> git.vomp.tv Git - vompserver.git/blob - thread.c
15 years that line of code has been waiting to crash
[vompserver.git] / thread.c
1 /*
2     Copyright 2004-2008 Chris Tallon
3
4     This file is part of VOMP.
5
6     VOMP is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     VOMP is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with VOMP; if not, write to the Free Software
18     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19 */
20
21 #include "thread.h"
22
23 // Undeclared functions, only for use in this file to start the thread
24 void threadInternalStart(void *arg)
25 {
26   // I don't want signals
27   sigset_t sigs;
28   sigfillset(&sigs);
29   pthread_sigmask(SIG_BLOCK, &sigs, NULL);
30
31   Thread *t = (Thread *)arg;
32   t->threadInternalStart2();
33 }
34
35 void Thread::threadInternalStart2()
36 {
37   threadMethod();
38   this->threadPostStopCleanup();
39 }
40
41 Thread::Thread()
42 {
43   threadActive = 0;
44 }
45
46 int Thread::threadStart()
47 {
48   pthread_cond_init(&threadCond, NULL);
49   pthread_mutex_init(&threadCondMutex, NULL);
50
51   threadActive = 1;
52   if (pthread_create(&pthread, NULL, (void*(*)(void*))threadInternalStart, (void *)this) == -1) return 0;
53   return 1;
54 }
55
56 void Thread::threadStop()
57 {
58   threadActive = 0;
59   // Signal thread here in case it's waiting
60   threadSignal();
61   pthread_join(pthread, NULL);
62 }
63
64 void Thread::threadCancel()
65 {
66   threadActive = 0;
67   pthread_cancel(pthread);
68   pthread_join(pthread, NULL);
69   this->threadPostStopCleanup(); // thread was cancelled, did not run post-stop above
70 }
71
72 void Thread::threadCheckExit()
73 {
74   if (!threadActive) pthread_exit(NULL);
75 }
76
77 char Thread::threadIsActive()
78 {
79   return threadActive;
80 }
81
82 void Thread::threadSignal()
83 {
84   pthread_mutex_lock(&threadCondMutex);
85   pthread_cond_signal(&threadCond);
86   pthread_mutex_unlock(&threadCondMutex);
87 }
88
89 void Thread::threadSignalNoLock()
90 {
91   pthread_cond_signal(&threadCond);
92 }
93
94 void Thread::threadWaitForSignal()
95 {
96   pthread_cond_wait(&threadCond, &threadCondMutex);
97 }
98
99 void Thread::threadDetach()
100 {
101   pthread_detach(pthread);
102 }
103
104 void Thread::threadLock()
105 {
106   pthread_mutex_lock(&threadCondMutex);
107 }
108
109 void Thread::threadUnlock()
110 {
111   pthread_mutex_unlock(&threadCondMutex);
112 }
113
114