]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
Semaphores are no longer used, remove:
[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 /*
184  * prio can be used for setting scheeduling policy but...
185  * it seems to be optional in POSIX threads and Solaris
186  * for example just ignores it.
187  * More then that priority is not needed even in lwp threads.
188  */
189 empth_t *
190 empth_create(int prio, void (*entry)(void *), int size, int flags,
191              char *name, void *ud)
192 {
193     pthread_t t;
194     pthread_attr_t attr;
195     empth_t *ctx;
196     int eno;
197
198     empth_status("creating new thread %s", name);
199
200     ctx = malloc(sizeof(empth_t));
201     if (!ctx) {
202         logerror("not enough memory to create thread %s", name);
203         return NULL;
204     }
205     ctx->name = strdup(name);
206     ctx->ud = ud;
207     ctx->state = 0;
208     ctx->ep = entry;
209
210     eno = pthread_attr_init(&attr);
211     if (eno) {
212         logerror("can not create thread attribute %s: %s",
213                  name, strerror(eno));
214         goto bad;
215     }
216     if (size < PTHREAD_STACK_MIN)
217         size = PTHREAD_STACK_MIN;
218     pthread_attr_setstacksize(&attr, size);
219     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
220
221     eno = pthread_create(&t, &attr, empth_start, ctx);
222     if (eno) {
223         logerror("can not create thread: %s: %s", name, strerror(eno));
224         goto bad;
225     }
226     empth_status("new thread id is %ld", (long)t);
227     empth_yield();
228     return ctx;
229
230   bad:
231     pthread_attr_destroy(&attr);
232     free(ctx);
233     return NULL;
234 }
235
236
237 static void
238 empth_restorectx(void)
239 {
240     empth_t *ctx_ptr;
241
242     ctx_ptr = pthread_getspecific(ctx_key);
243     *udata = ctx_ptr->ud;
244     if (ctx_ptr->state == EMPTH_KILLED) {
245         empth_status("i am dead");
246         empth_exit();
247     }
248     ctx_ptr->state = 0;
249     empth_status("context restored");
250 }
251
252 empth_t *
253 empth_self(void)
254 {
255     return pthread_getspecific(ctx_key);
256 }
257
258 void
259 empth_exit(void)
260 {
261     empth_t *ctx = pthread_getspecific(ctx_key);
262
263     empth_status("empth_exit");
264     pthread_mutex_unlock(&mtx_ctxsw);
265     free(ctx->name);
266     free(ctx);
267     pthread_exit(0);
268 }
269
270 void
271 empth_yield(void)
272 {
273     pthread_mutex_unlock(&mtx_ctxsw);
274     pthread_mutex_lock(&mtx_ctxsw);
275     empth_restorectx();
276 }
277
278 void
279 empth_terminate(empth_t *a)
280 {
281     empth_status("killing thread %s", a->name);
282     a->state = EMPTH_KILLED;
283     pthread_kill(a->id, SIGALRM);
284 }
285
286 void
287 empth_select(int fd, int flags)
288 {
289
290     fd_set readmask;
291     fd_set writemask;
292     struct timeval tv;
293     int n;
294
295     pthread_mutex_unlock(&mtx_ctxsw);
296     empth_status("%s select on %d",
297                  flags == EMPTH_FD_READ ? "read" : "write", fd);
298     while (1) {
299         tv.tv_sec = 1000000;
300         tv.tv_usec = 0;
301
302         FD_ZERO(&readmask);
303         FD_ZERO(&writemask);
304
305         switch (flags) {
306         case EMPTH_FD_READ:
307             FD_SET(fd, &readmask);
308             break;
309         case EMPTH_FD_WRITE:
310             FD_SET(fd, &writemask);
311             break;
312         default:
313             logerror("bad flag %d passed to empth_select", flags);
314             empth_exit();
315         }
316
317         n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
318
319         if (n < 0) {
320             if (errno == EINTR) {
321                 /* go handle the signal */
322                 empth_status("select broken by signal");
323                 goto done;
324                 return;
325             }
326             /* strange but we dont get EINTR on select broken by signal */
327             empth_status("select failed (%s)", strerror(errno));
328             goto done;
329             return;
330         }
331
332         if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
333             empth_status("input ready");
334             break;
335         }
336         if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
337             empth_status("output ready");
338             break;
339         }
340     }
341
342   done:
343     pthread_mutex_lock(&mtx_ctxsw);
344     empth_restorectx();
345 }
346
347 static void
348 empth_alarm(int sig)
349 {
350     /*
351      * Nothing to do --- we handle this signal just to let
352      * empth_wakeup() and empth_terminate() interrupt system calls.
353      */
354 }
355
356 void
357 empth_wakeup(empth_t *a)
358 {
359     empth_status("waking up thread %s", a->name);
360     if (a->state == 0)
361         a->state = EMPTH_INTR;
362     pthread_kill(a->id, SIGALRM);
363 }
364
365 int
366 empth_sleep(time_t until)
367 {
368     empth_t *ctx = pthread_getspecific(ctx_key);
369     struct timeval tv;
370     int res;
371
372     empth_status("going to sleep %ld sec", until - time(0));
373     pthread_mutex_unlock(&mtx_ctxsw);
374     do {
375         tv.tv_sec = until - time(NULL);
376         tv.tv_usec = 0;
377         res = select(0, NULL, NULL, NULL, &tv);
378     } while (res < 0 && ctx->state == 0);
379     empth_status("sleep done. Waiting for lock");
380     pthread_mutex_lock(&mtx_ctxsw);
381     empth_restorectx();
382     return res;
383 }
384
385 int
386 empth_wait_for_signal(void)
387 {
388     sigset_t set;
389     int sig, err;
390
391     sigemptyset(&set);
392     sigaddset(&set, SIGHUP);
393     sigaddset(&set, SIGINT);
394     sigaddset(&set, SIGTERM);
395     pthread_mutex_unlock(&mtx_ctxsw);
396     for (;;) {
397         empth_status("waiting for signals");
398         err = sigwait(&set, &sig);
399         if (CANT_HAPPEN(err)) {
400             sleep(60);
401             continue;
402         }
403         empth_status("got awaited signal %d", sig);
404         pthread_mutex_lock(&mtx_ctxsw);
405         empth_restorectx();
406         return sig;
407     }
408 }
409
410 empth_rwlock_t *
411 empth_rwlock_create(char *name)
412 {
413     empth_rwlock_t *rwlock;
414
415     rwlock = malloc(sizeof(*rwlock));
416     if (!rwlock)
417         return NULL;
418
419     if (pthread_rwlock_init(&rwlock->lock, NULL) != 0) {
420         free(rwlock);
421         return NULL;
422     }
423
424     rwlock->name = strdup(name);
425     return rwlock;
426 }
427
428 void
429 empth_rwlock_destroy(empth_rwlock_t *rwlock)
430 {
431     pthread_rwlock_destroy(&rwlock->lock);
432     free(rwlock->name);
433     free(rwlock);
434 }
435
436 void
437 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
438 {
439     pthread_mutex_unlock(&mtx_ctxsw);
440     pthread_rwlock_wrlock(&rwlock->lock);
441     pthread_mutex_lock(&mtx_ctxsw);
442     empth_restorectx();
443 }
444
445 void
446 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
447 {
448     pthread_mutex_unlock(&mtx_ctxsw);
449     pthread_rwlock_rdlock(&rwlock->lock);
450     pthread_mutex_lock(&mtx_ctxsw);
451     empth_restorectx();
452 }
453
454 void
455 empth_rwlock_unlock(empth_rwlock_t *rwlock)
456 {
457     pthread_rwlock_unlock(&rwlock->lock);
458 }