]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
Remove the concept of thread priorities from empthread.h. Only LWP
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2007, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *
6  *  This program 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  *  This program 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 this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ---
21  *
22  *  See files README, COPYING and CREDITS in the root of the source
23  *  tree for related information and legal notices.  It is expected
24  *  that future projects/authors will amend these files as needed.
25  *
26  *  ---
27  *
28  *  pthread.c: Interface from Empire threads to POSIX threads
29  * 
30  *  Known contributors to this file:
31  *     Sasha Mikheev
32  *     Steve McClure, 1998
33  *     Markus Armbruster, 2005-2007
34  *     Ron Koenderink, 2007
35  */
36
37 /* Required for PTHREAD_STACK_MIN on some systems, e.g. Solaris: */
38 #define _XOPEN_SOURCE 500
39
40 #include <config.h>
41
42 #include <errno.h>
43 #include <limits.h>
44 #include <pthread.h>
45 #include <signal.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <sys/types.h>
51 #if !defined(_WIN32)
52 #include <sys/time.h>
53 #include <unistd.h>
54 #endif
55
56 #include "misc.h"
57 #include "empthread.h"
58 #include "prototypes.h"
59
60 #define EMPTH_KILLED  1
61 #define EMPTH_INTR 2
62
63 struct empth_t {
64     char *name;                 /* thread name */
65     void *ud;                   /* user data */
66     int state;                  /* my state */
67     void (*ep)(void *);         /* entry point */
68     pthread_t id;               /* thread id */
69 };
70
71 struct empth_rwlock_t {
72     char *name;
73     pthread_rwlock_t lock;
74 };
75
76 /* Thread-specific data key */
77 static pthread_key_t ctx_key;
78
79 /* Flags that were passed to empth_init() */
80 static int empth_flags;
81
82 /* Pointer to thread context variable */
83 static void **udata;
84
85 /*
86  * Non-preemption mutex.
87  * Empire code outside this file is only executed while holding this
88  * mutex.  This makes sure Empire code is never preempted by Empire
89  * code.
90  */
91 static pthread_mutex_t mtx_ctxsw;
92
93 static void empth_status(char *format, ...)
94     ATTRIBUTE((format (printf, 1, 2)));
95 static void empth_alarm(int sig);
96
97 static void *
98 empth_start(void *arg)
99 {
100     empth_t *ctx = arg;
101
102     ctx->id = pthread_self();
103     pthread_setspecific(ctx_key, ctx);
104     pthread_mutex_lock(&mtx_ctxsw);
105     *udata = ctx->ud;
106     ctx->ep(ctx->ud);
107     empth_exit();
108     return NULL;
109 }
110
111 static void
112 empth_status(char *format, ...)
113 {
114     va_list ap;
115     static struct timeval startTime;
116     struct timeval tv;
117     char buf[1024];
118     int sec, msec;
119     empth_t *a;
120
121     va_start(ap, format);
122     if (empth_flags & EMPTH_PRINT) {
123         if (startTime.tv_sec == 0)
124             gettimeofday(&startTime, 0);
125         gettimeofday(&tv, 0);
126         sec = tv.tv_sec - startTime.tv_sec;
127         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
128         if (msec < 0) {
129             sec++;
130             msec += 1000;
131         }
132         vsprintf(buf, format, ap);
133         a = empth_self();
134         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
135                a->name, buf);
136
137     }
138     va_end(ap);
139 }
140
141
142 int
143 empth_init(void **ctx_ptr, int flags)
144 {
145     empth_t *ctx;
146     sigset_t set;
147     struct sigaction act;
148
149     empth_flags = flags;
150     udata = ctx_ptr;
151
152     empth_init_signals();
153     sigemptyset(&set);
154     sigaddset(&set, SIGHUP);
155     sigaddset(&set, SIGINT);
156     sigaddset(&set, SIGTERM);
157     pthread_sigmask(SIG_BLOCK, &set, NULL);
158     act.sa_flags = 0;
159     sigemptyset(&act.sa_mask);
160     act.sa_handler = empth_alarm;
161     sigaction(SIGALRM, &act, NULL);
162
163     pthread_key_create(&ctx_key, NULL);
164     pthread_mutex_init(&mtx_ctxsw, NULL);
165
166     ctx = malloc(sizeof(empth_t));
167     if (!ctx) {
168         logerror("pthread init failed: not enough memory");
169         exit(1);
170     }
171     ctx->name = "Main";
172     ctx->ep = 0;
173     ctx->ud = 0;
174     ctx->id = pthread_self();
175     ctx->state = 0;
176     pthread_setspecific(ctx_key, ctx);
177     pthread_mutex_lock(&mtx_ctxsw);
178     logerror("pthreads initialized");
179     return 0;
180 }
181
182
183 empth_t *
184 empth_create(void (*entry)(void *), int size, int flags,
185              char *name, void *ud)
186 {
187     pthread_t t;
188     pthread_attr_t attr;
189     empth_t *ctx;
190     int eno;
191
192     empth_status("creating new thread %s", name);
193
194     ctx = malloc(sizeof(empth_t));
195     if (!ctx) {
196         logerror("not enough memory to create thread %s", name);
197         return NULL;
198     }
199     ctx->name = strdup(name);
200     ctx->ud = ud;
201     ctx->state = 0;
202     ctx->ep = entry;
203
204     eno = pthread_attr_init(&attr);
205     if (eno) {
206         logerror("can not create thread attribute %s: %s",
207                  name, strerror(eno));
208         goto bad;
209     }
210     if (size < PTHREAD_STACK_MIN)
211         size = PTHREAD_STACK_MIN;
212     pthread_attr_setstacksize(&attr, size);
213     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
214
215     eno = pthread_create(&t, &attr, empth_start, ctx);
216     if (eno) {
217         logerror("can not create thread: %s: %s", name, strerror(eno));
218         goto bad;
219     }
220     empth_status("new thread id is %ld", (long)t);
221     empth_yield();
222     return ctx;
223
224   bad:
225     pthread_attr_destroy(&attr);
226     free(ctx);
227     return NULL;
228 }
229
230
231 static void
232 empth_restorectx(void)
233 {
234     empth_t *ctx_ptr;
235
236     ctx_ptr = pthread_getspecific(ctx_key);
237     *udata = ctx_ptr->ud;
238     if (ctx_ptr->state == EMPTH_KILLED) {
239         empth_status("i am dead");
240         empth_exit();
241     }
242     ctx_ptr->state = 0;
243     empth_status("context restored");
244 }
245
246 empth_t *
247 empth_self(void)
248 {
249     return pthread_getspecific(ctx_key);
250 }
251
252 void
253 empth_exit(void)
254 {
255     empth_t *ctx = pthread_getspecific(ctx_key);
256
257     empth_status("empth_exit");
258     pthread_mutex_unlock(&mtx_ctxsw);
259     free(ctx->name);
260     free(ctx);
261     pthread_exit(0);
262 }
263
264 void
265 empth_yield(void)
266 {
267     pthread_mutex_unlock(&mtx_ctxsw);
268     pthread_mutex_lock(&mtx_ctxsw);
269     empth_restorectx();
270 }
271
272 void
273 empth_terminate(empth_t *a)
274 {
275     empth_status("killing thread %s", a->name);
276     a->state = EMPTH_KILLED;
277     pthread_kill(a->id, SIGALRM);
278 }
279
280 void
281 empth_select(int fd, int flags)
282 {
283
284     fd_set readmask;
285     fd_set writemask;
286     struct timeval tv;
287     int n;
288
289     pthread_mutex_unlock(&mtx_ctxsw);
290     empth_status("%s select on %d",
291                  flags == EMPTH_FD_READ ? "read" : "write", fd);
292     while (1) {
293         tv.tv_sec = 1000000;
294         tv.tv_usec = 0;
295
296         FD_ZERO(&readmask);
297         FD_ZERO(&writemask);
298
299         switch (flags) {
300         case EMPTH_FD_READ:
301             FD_SET(fd, &readmask);
302             break;
303         case EMPTH_FD_WRITE:
304             FD_SET(fd, &writemask);
305             break;
306         default:
307             logerror("bad flag %d passed to empth_select", flags);
308             empth_exit();
309         }
310
311         n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
312
313         if (n < 0) {
314             if (errno == EINTR) {
315                 /* go handle the signal */
316                 empth_status("select broken by signal");
317                 goto done;
318                 return;
319             }
320             /* strange but we dont get EINTR on select broken by signal */
321             empth_status("select failed (%s)", strerror(errno));
322             goto done;
323             return;
324         }
325
326         if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
327             empth_status("input ready");
328             break;
329         }
330         if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
331             empth_status("output ready");
332             break;
333         }
334     }
335
336   done:
337     pthread_mutex_lock(&mtx_ctxsw);
338     empth_restorectx();
339 }
340
341 static void
342 empth_alarm(int sig)
343 {
344     /*
345      * Nothing to do --- we handle this signal just to let
346      * empth_wakeup() and empth_terminate() interrupt system calls.
347      */
348 }
349
350 void
351 empth_wakeup(empth_t *a)
352 {
353     empth_status("waking up thread %s", a->name);
354     if (a->state == 0)
355         a->state = EMPTH_INTR;
356     pthread_kill(a->id, SIGALRM);
357 }
358
359 int
360 empth_sleep(time_t until)
361 {
362     empth_t *ctx = pthread_getspecific(ctx_key);
363     struct timeval tv;
364     int res;
365
366     empth_status("going to sleep %ld sec", until - time(0));
367     pthread_mutex_unlock(&mtx_ctxsw);
368     do {
369         tv.tv_sec = until - time(NULL);
370         tv.tv_usec = 0;
371         res = select(0, NULL, NULL, NULL, &tv);
372     } while (res < 0 && ctx->state == 0);
373     empth_status("sleep done. Waiting for lock");
374     pthread_mutex_lock(&mtx_ctxsw);
375     empth_restorectx();
376     return res;
377 }
378
379 int
380 empth_wait_for_signal(void)
381 {
382     sigset_t set;
383     int sig, err;
384
385     sigemptyset(&set);
386     sigaddset(&set, SIGHUP);
387     sigaddset(&set, SIGINT);
388     sigaddset(&set, SIGTERM);
389     pthread_mutex_unlock(&mtx_ctxsw);
390     for (;;) {
391         empth_status("waiting for signals");
392         err = sigwait(&set, &sig);
393         if (CANT_HAPPEN(err)) {
394             sleep(60);
395             continue;
396         }
397         empth_status("got awaited signal %d", sig);
398         pthread_mutex_lock(&mtx_ctxsw);
399         empth_restorectx();
400         return sig;
401     }
402 }
403
404 empth_rwlock_t *
405 empth_rwlock_create(char *name)
406 {
407     empth_rwlock_t *rwlock;
408
409     rwlock = malloc(sizeof(*rwlock));
410     if (!rwlock)
411         return NULL;
412
413     if (pthread_rwlock_init(&rwlock->lock, NULL) != 0) {
414         free(rwlock);
415         return NULL;
416     }
417
418     rwlock->name = strdup(name);
419     return rwlock;
420 }
421
422 void
423 empth_rwlock_destroy(empth_rwlock_t *rwlock)
424 {
425     pthread_rwlock_destroy(&rwlock->lock);
426     free(rwlock->name);
427     free(rwlock);
428 }
429
430 void
431 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
432 {
433     pthread_mutex_unlock(&mtx_ctxsw);
434     pthread_rwlock_wrlock(&rwlock->lock);
435     pthread_mutex_lock(&mtx_ctxsw);
436     empth_restorectx();
437 }
438
439 void
440 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
441 {
442     pthread_mutex_unlock(&mtx_ctxsw);
443     pthread_rwlock_rdlock(&rwlock->lock);
444     pthread_mutex_lock(&mtx_ctxsw);
445     empth_restorectx();
446 }
447
448 void
449 empth_rwlock_unlock(empth_rwlock_t *rwlock)
450 {
451     pthread_rwlock_unlock(&rwlock->lock);
452 }