]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
3378b50bc7ba75ec8c191afe074e7a39a8f343d7
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2009, 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-2009
34  *     Ron Koenderink, 2007-2009
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/select.h>
51 #include <unistd.h>
52 #include "misc.h"
53 #include "empthread.h"
54 #include "prototypes.h"
55
56 struct empth_t {
57     char *name;                 /* thread name */
58     void *ud;                   /* user data */
59     int wakeup;
60     void (*ep)(void *);         /* entry point */
61     pthread_t id;               /* thread id */
62 };
63
64 struct empth_rwlock_t {
65     /* Can't use pthread_rwlock_t, because it needn't prefer writers */
66     char *name;
67     int nread;                  /* #active readers */
68     int nwrite;                 /* total #writers (active and waiting) */
69     pthread_cond_t can_read;
70     pthread_cond_t can_write;
71 };
72
73 /* Thread-specific data key */
74 static pthread_key_t ctx_key;
75
76 /* Flags that were passed to empth_init() */
77 static int empth_flags;
78
79 /* Pointer to thread context variable */
80 static void **udata;
81
82 /*
83  * Non-preemption mutex.
84  * Empire code outside this file is only executed while holding this
85  * mutex.  This makes sure Empire code is never preempted by Empire
86  * code.
87  */
88 static pthread_mutex_t mtx_ctxsw;
89
90 static void empth_status(char *format, ...)
91     ATTRIBUTE((format (printf, 1, 2)));
92 static void empth_alarm(int sig);
93
94 static void *
95 empth_start(void *arg)
96 {
97     empth_t *ctx = arg;
98
99     ctx->id = pthread_self();
100     pthread_setspecific(ctx_key, ctx);
101     pthread_mutex_lock(&mtx_ctxsw);
102     *udata = ctx->ud;
103     ctx->ep(ctx->ud);
104     empth_exit();
105     return NULL;
106 }
107
108 static void
109 empth_status(char *format, ...)
110 {
111     va_list ap;
112     static struct timeval startTime;
113     struct timeval tv;
114     char buf[1024];
115     int sec, msec;
116     empth_t *a;
117
118     va_start(ap, format);
119     if (empth_flags & EMPTH_PRINT) {
120         if (startTime.tv_sec == 0)
121             gettimeofday(&startTime, 0);
122         gettimeofday(&tv, 0);
123         sec = tv.tv_sec - startTime.tv_sec;
124         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
125         if (msec < 0) {
126             sec++;
127             msec += 1000;
128         }
129         vsprintf(buf, format, ap);
130         a = empth_self();
131         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
132                a->name, buf);
133
134     }
135     va_end(ap);
136 }
137
138
139 int
140 empth_init(void **ctx_ptr, int flags)
141 {
142     empth_t *ctx;
143     sigset_t set;
144     struct sigaction act;
145
146     empth_flags = flags;
147     udata = ctx_ptr;
148
149     empth_init_signals();
150     sigemptyset(&set);
151     sigaddset(&set, SIGHUP);
152     sigaddset(&set, SIGINT);
153     sigaddset(&set, SIGTERM);
154     pthread_sigmask(SIG_BLOCK, &set, NULL);
155     act.sa_flags = 0;
156     sigemptyset(&act.sa_mask);
157     act.sa_handler = empth_alarm;
158     sigaction(SIGALRM, &act, NULL);
159
160     pthread_key_create(&ctx_key, NULL);
161     pthread_mutex_init(&mtx_ctxsw, NULL);
162
163     ctx = malloc(sizeof(empth_t));
164     if (!ctx) {
165         logerror("pthread init failed: not enough memory");
166         exit(1);
167     }
168     ctx->name = "Main";
169     ctx->ep = 0;
170     ctx->ud = 0;
171     ctx->id = pthread_self();
172     ctx->wakeup = 0;
173     pthread_setspecific(ctx_key, ctx);
174     pthread_mutex_lock(&mtx_ctxsw);
175     logerror("pthreads initialized");
176     return 0;
177 }
178
179
180 empth_t *
181 empth_create(void (*entry)(void *), int size, int flags,
182              char *name, void *ud)
183 {
184     pthread_t t;
185     pthread_attr_t attr;
186     empth_t *ctx;
187     int eno;
188
189     empth_status("creating new thread %s", name);
190
191     ctx = malloc(sizeof(empth_t));
192     if (!ctx) {
193         logerror("not enough memory to create thread %s", name);
194         return NULL;
195     }
196     ctx->name = strdup(name);
197     ctx->ud = ud;
198     ctx->wakeup = 0;
199     ctx->ep = entry;
200
201     eno = pthread_attr_init(&attr);
202     if (eno) {
203         logerror("can not create thread attribute %s: %s",
204                  name, strerror(eno));
205         goto bad;
206     }
207     if (size < PTHREAD_STACK_MIN)
208         size = PTHREAD_STACK_MIN;
209     pthread_attr_setstacksize(&attr, size);
210     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
211
212     eno = pthread_create(&t, &attr, empth_start, ctx);
213     if (eno) {
214         logerror("can not create thread: %s: %s", name, strerror(eno));
215         goto bad;
216     }
217     empth_status("new thread id is %ld", (long)t);
218     empth_yield();
219     return ctx;
220
221   bad:
222     pthread_attr_destroy(&attr);
223     free(ctx);
224     return NULL;
225 }
226
227
228 static void
229 empth_restorectx(void)
230 {
231     empth_t *ctx_ptr;
232
233     ctx_ptr = pthread_getspecific(ctx_key);
234     *udata = ctx_ptr->ud;
235     ctx_ptr->wakeup = 0;
236     empth_status("context restored");
237 }
238
239 empth_t *
240 empth_self(void)
241 {
242     return pthread_getspecific(ctx_key);
243 }
244
245 char *
246 empth_name(empth_t *thread)
247 {
248     return thread->name;
249 }
250
251 void
252 empth_set_name(empth_t *thread, char *name)
253 {
254     if (thread->name)
255         free(thread->name);
256     thread->name = strdup(name);
257 }
258
259 void
260 empth_exit(void)
261 {
262     empth_t *ctx = pthread_getspecific(ctx_key);
263
264     empth_status("empth_exit");
265     pthread_mutex_unlock(&mtx_ctxsw);
266     free(ctx->name);
267     free(ctx);
268     pthread_exit(0);
269 }
270
271 void
272 empth_yield(void)
273 {
274     pthread_mutex_unlock(&mtx_ctxsw);
275     pthread_mutex_lock(&mtx_ctxsw);
276     empth_restorectx();
277 }
278
279 int
280 empth_select(int fd, int flags, struct timeval *timeout)
281 {
282     fd_set readmask;
283     fd_set writemask;
284     struct timeval tv;
285     int n;
286     empth_t *ctx;
287     int res = 0;
288
289     pthread_mutex_unlock(&mtx_ctxsw);
290     empth_status("select on %d for %d", fd, flags);
291
292 again:
293     FD_ZERO(&readmask);
294     FD_ZERO(&writemask);
295     if (flags & EMPTH_FD_READ)
296         FD_SET(fd, &readmask);
297     if (flags & EMPTH_FD_WRITE)
298         FD_SET(fd, &writemask);
299
300     if (timeout)
301         tv = *timeout;
302     n = select(fd + 1, &readmask, &writemask, NULL, timeout ? &tv : NULL);
303     if (n < 0) {
304         ctx = pthread_getspecific(ctx_key);
305         if (ctx->wakeup) {
306             empth_status("select woken up");
307             res = 0;
308         } else if (errno == EINTR) {
309             empth_status("select broken by signal");
310             goto again;
311         } else {
312             empth_status("select failed (%s)", strerror(errno));
313             res = -1;
314         }
315     } else if (n == 0) {
316         empth_status("select timed out");
317         res = 0;
318     } else if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
319         empth_status("input ready");
320         res = 1;
321     } else if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
322         empth_status("output ready");
323         res = 1;
324     }
325
326     pthread_mutex_lock(&mtx_ctxsw);
327     empth_restorectx();
328     return res;
329 }
330
331 static void
332 empth_alarm(int sig)
333 {
334     /*
335      * Nothing to do --- we handle this signal just to let
336      * empth_wakeup() interrupt system calls.
337      */
338 }
339
340 void
341 empth_wakeup(empth_t *a)
342 {
343     empth_status("waking up thread %s", a->name);
344     a->wakeup = 1;
345     pthread_kill(a->id, SIGALRM);
346 }
347
348 int
349 empth_sleep(time_t until)
350 {
351     empth_t *ctx = pthread_getspecific(ctx_key);
352     time_t now;
353     struct timeval tv;
354     int res;
355
356     pthread_mutex_unlock(&mtx_ctxsw);
357     do {
358         now = time(NULL);
359         tv.tv_sec = until >= now ? until - now : 0;
360         tv.tv_usec = 0;
361         empth_status("going to sleep %ld sec", (long)tv.tv_sec);
362         res = select(0, NULL, NULL, NULL, &tv);
363     } while (res < 0 && !ctx->wakeup);
364     empth_status("sleep done. Waiting for lock");
365     pthread_mutex_lock(&mtx_ctxsw);
366     empth_restorectx();
367     return res;
368 }
369
370 int
371 empth_wait_for_signal(void)
372 {
373     sigset_t set;
374     int sig, err;
375
376     sigemptyset(&set);
377     sigaddset(&set, SIGHUP);
378     sigaddset(&set, SIGINT);
379     sigaddset(&set, SIGTERM);
380     pthread_mutex_unlock(&mtx_ctxsw);
381     for (;;) {
382         empth_status("waiting for signals");
383         err = sigwait(&set, &sig);
384         if (CANT_HAPPEN(err)) {
385             sleep(60);
386             continue;
387         }
388         empth_status("got awaited signal %d", sig);
389         pthread_mutex_lock(&mtx_ctxsw);
390         empth_restorectx();
391         return sig;
392     }
393 }
394
395 empth_rwlock_t *
396 empth_rwlock_create(char *name)
397 {
398     empth_rwlock_t *rwlock;
399
400     rwlock = malloc(sizeof(*rwlock));
401     if (!rwlock)
402         return NULL;
403
404     if (pthread_cond_init(&rwlock->can_read, NULL) != 0
405         || pthread_cond_init(&rwlock->can_write, NULL) != 0) {
406         free(rwlock);
407         return NULL;
408     }
409
410     rwlock->name = strdup(name);
411     rwlock->nread = rwlock->nwrite = 0;
412     return rwlock;
413 }
414
415 void
416 empth_rwlock_destroy(empth_rwlock_t *rwlock)
417 {
418     pthread_cond_destroy(&rwlock->can_read);
419     pthread_cond_destroy(&rwlock->can_write);
420     free(rwlock->name);
421     free(rwlock);
422 }
423
424 void
425 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
426 {
427     empth_status("wrlock %s %d %d",
428                  rwlock->name, rwlock->nread, rwlock->nwrite);
429     rwlock->nwrite++;
430     while (rwlock->nread != 0 || rwlock->nwrite != 1) {
431         empth_status("waiting for wrlock %s", rwlock->name);
432         pthread_cond_wait(&rwlock->can_write, &mtx_ctxsw);
433         empth_status("got wrlock %s %d %d",
434                  rwlock->name, rwlock->nread, rwlock->nwrite);
435         empth_restorectx();
436     }
437 }
438
439 void
440 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
441 {
442     empth_status("rdlock %s %d %d",
443                  rwlock->name, rwlock->nread, rwlock->nwrite);
444     while (rwlock->nwrite) {
445         empth_status("waiting for rdlock %s", rwlock->name);
446         pthread_cond_wait(&rwlock->can_read, &mtx_ctxsw);
447         empth_status("got rdlock %s %d %d",
448                      rwlock->name, rwlock->nread, rwlock->nwrite);
449         empth_restorectx();
450     }
451     rwlock->nread++;
452 }
453
454 void
455 empth_rwlock_unlock(empth_rwlock_t *rwlock)
456 {
457     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
458         return;
459     if (rwlock->nread) {        /* holding read lock */
460         if (!--rwlock->nread)
461             pthread_cond_signal(&rwlock->can_write);
462     } else {
463         rwlock->nwrite--;
464         pthread_cond_signal(&rwlock->can_write);
465     }
466     if (rwlock->nwrite == 0)
467         pthread_cond_broadcast(&rwlock->can_read);
468 }