]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
Update known contributors comments
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire 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 3 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, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  pthread.c: Interface from Empire threads to POSIX threads
28  *
29  *  Known contributors to this file:
30  *     Sasha Mikheev
31  *     Steve McClure, 1998
32  *     Markus Armbruster, 2005-2010
33  *     Ron Koenderink, 2007-2009
34  */
35
36 /* Required for PTHREAD_STACK_MIN on some systems, e.g. Solaris: */
37 #define _XOPEN_SOURCE 500
38
39 #include <config.h>
40
41 #include <errno.h>
42 #include <limits.h>
43 #include <pthread.h>
44 #include <signal.h>
45 #include <stdarg.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/select.h>
50 #include <unistd.h>
51 #include "misc.h"
52 #include "empthread.h"
53 #include "file.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     ef_make_stale();
191
192     ctx = malloc(sizeof(empth_t));
193     if (!ctx) {
194         logerror("not enough memory to create thread %s", name);
195         return NULL;
196     }
197     ctx->name = strdup(name);
198     ctx->ud = ud;
199     ctx->wakeup = 0;
200     ctx->ep = entry;
201
202     eno = pthread_attr_init(&attr);
203     if (eno) {
204         logerror("can not create thread attribute %s: %s",
205                  name, strerror(eno));
206         goto bad;
207     }
208     if (size < PTHREAD_STACK_MIN)
209         size = PTHREAD_STACK_MIN;
210     pthread_attr_setstacksize(&attr, size);
211     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
212
213     eno = pthread_create(&t, &attr, empth_start, ctx);
214     if (eno) {
215         logerror("can not create thread: %s: %s", name, strerror(eno));
216         goto bad;
217     }
218     empth_status("new thread id is %ld", (long)t);
219     empth_yield();
220     return ctx;
221
222   bad:
223     pthread_attr_destroy(&attr);
224     free(ctx);
225     return NULL;
226 }
227
228
229 static void
230 empth_restorectx(void)
231 {
232     empth_t *ctx_ptr;
233
234     ctx_ptr = pthread_getspecific(ctx_key);
235     *udata = ctx_ptr->ud;
236     ctx_ptr->wakeup = 0;
237     empth_status("context restored");
238 }
239
240 empth_t *
241 empth_self(void)
242 {
243     return pthread_getspecific(ctx_key);
244 }
245
246 char *
247 empth_name(empth_t *thread)
248 {
249     return thread->name;
250 }
251
252 void
253 empth_set_name(empth_t *thread, char *name)
254 {
255     if (thread->name)
256         free(thread->name);
257     thread->name = strdup(name);
258 }
259
260 void
261 empth_exit(void)
262 {
263     empth_t *ctx = pthread_getspecific(ctx_key);
264
265     empth_status("empth_exit");
266     ef_make_stale();
267     pthread_mutex_unlock(&mtx_ctxsw);
268     free(ctx->name);
269     free(ctx);
270     pthread_exit(0);
271 }
272
273 void
274 empth_yield(void)
275 {
276     ef_make_stale();
277     pthread_mutex_unlock(&mtx_ctxsw);
278     pthread_mutex_lock(&mtx_ctxsw);
279     empth_restorectx();
280 }
281
282 int
283 empth_select(int fd, int flags, struct timeval *timeout)
284 {
285     fd_set readmask;
286     fd_set writemask;
287     struct timeval tv;
288     int n;
289     empth_t *ctx;
290     int res = 0;
291
292     ef_make_stale();
293     pthread_mutex_unlock(&mtx_ctxsw);
294     empth_status("select on %d for %d", fd, flags);
295
296 again:
297     FD_ZERO(&readmask);
298     FD_ZERO(&writemask);
299     if (flags & EMPTH_FD_READ)
300         FD_SET(fd, &readmask);
301     if (flags & EMPTH_FD_WRITE)
302         FD_SET(fd, &writemask);
303
304     if (timeout)
305         tv = *timeout;
306     n = select(fd + 1, &readmask, &writemask, NULL, timeout ? &tv : NULL);
307     if (n < 0) {
308         ctx = pthread_getspecific(ctx_key);
309         if (ctx->wakeup) {
310             empth_status("select woken up");
311             res = 0;
312         } else if (errno == EINTR) {
313             empth_status("select broken by signal");
314             goto again;
315         } else {
316             empth_status("select failed (%s)", strerror(errno));
317             res = -1;
318         }
319     } else if (n == 0) {
320         empth_status("select timed out");
321         res = 0;
322     } else if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
323         empth_status("input ready");
324         res = 1;
325     } else if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
326         empth_status("output ready");
327         res = 1;
328     }
329
330     pthread_mutex_lock(&mtx_ctxsw);
331     empth_restorectx();
332     return res;
333 }
334
335 static void
336 empth_alarm(int sig)
337 {
338     /*
339      * Nothing to do --- we handle this signal just to let
340      * empth_wakeup() interrupt system calls.
341      */
342 }
343
344 void
345 empth_wakeup(empth_t *a)
346 {
347     empth_status("waking up thread %s", a->name);
348     a->wakeup = 1;
349     pthread_kill(a->id, SIGALRM);
350 }
351
352 int
353 empth_sleep(time_t until)
354 {
355     empth_t *ctx = pthread_getspecific(ctx_key);
356     time_t now;
357     struct timeval tv;
358     int res;
359
360     ef_make_stale();
361     pthread_mutex_unlock(&mtx_ctxsw);
362     do {
363         now = time(NULL);
364         tv.tv_sec = until >= now ? until - now : 0;
365         tv.tv_usec = 0;
366         empth_status("going to sleep %ld sec", (long)tv.tv_sec);
367         res = select(0, NULL, NULL, NULL, &tv);
368     } while (res < 0 && !ctx->wakeup);
369     empth_status("sleep done. Waiting for lock");
370     pthread_mutex_lock(&mtx_ctxsw);
371     empth_restorectx();
372     return res;
373 }
374
375 int
376 empth_wait_for_signal(void)
377 {
378     sigset_t set;
379     int sig, err;
380
381     ef_make_stale();
382     sigemptyset(&set);
383     sigaddset(&set, SIGHUP);
384     sigaddset(&set, SIGINT);
385     sigaddset(&set, SIGTERM);
386     pthread_mutex_unlock(&mtx_ctxsw);
387     for (;;) {
388         empth_status("waiting for signals");
389         err = sigwait(&set, &sig);
390         if (CANT_HAPPEN(err)) {
391             sleep(60);
392             continue;
393         }
394         empth_status("got awaited signal %d", sig);
395         pthread_mutex_lock(&mtx_ctxsw);
396         empth_restorectx();
397         return sig;
398     }
399 }
400
401 empth_rwlock_t *
402 empth_rwlock_create(char *name)
403 {
404     empth_rwlock_t *rwlock;
405
406     rwlock = malloc(sizeof(*rwlock));
407     if (!rwlock)
408         return NULL;
409
410     if (pthread_cond_init(&rwlock->can_read, NULL) != 0
411         || pthread_cond_init(&rwlock->can_write, NULL) != 0) {
412         free(rwlock);
413         return NULL;
414     }
415
416     rwlock->name = strdup(name);
417     rwlock->nread = rwlock->nwrite = 0;
418     return rwlock;
419 }
420
421 void
422 empth_rwlock_destroy(empth_rwlock_t *rwlock)
423 {
424     pthread_cond_destroy(&rwlock->can_read);
425     pthread_cond_destroy(&rwlock->can_write);
426     free(rwlock->name);
427     free(rwlock);
428 }
429
430 void
431 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
432 {
433     empth_status("wrlock %s %d %d",
434                  rwlock->name, rwlock->nread, rwlock->nwrite);
435     ef_make_stale();
436     rwlock->nwrite++;
437     while (rwlock->nread != 0 || rwlock->nwrite != 1) {
438         empth_status("waiting for wrlock %s", rwlock->name);
439         pthread_cond_wait(&rwlock->can_write, &mtx_ctxsw);
440         empth_status("got wrlock %s %d %d",
441                      rwlock->name, rwlock->nread, rwlock->nwrite);
442         empth_restorectx();
443     }
444 }
445
446 void
447 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
448 {
449     empth_status("rdlock %s %d %d",
450                  rwlock->name, rwlock->nread, rwlock->nwrite);
451     ef_make_stale();
452     while (rwlock->nwrite) {
453         empth_status("waiting for rdlock %s", rwlock->name);
454         pthread_cond_wait(&rwlock->can_read, &mtx_ctxsw);
455         empth_status("got rdlock %s %d %d",
456                      rwlock->name, rwlock->nread, rwlock->nwrite);
457         empth_restorectx();
458     }
459     rwlock->nread++;
460 }
461
462 void
463 empth_rwlock_unlock(empth_rwlock_t *rwlock)
464 {
465     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
466         return;
467     if (rwlock->nread) {        /* holding read lock */
468         if (!--rwlock->nread)
469             pthread_cond_signal(&rwlock->can_write);
470     } else {
471         rwlock->nwrite--;
472         pthread_cond_signal(&rwlock->can_write);
473     }
474     if (rwlock->nwrite == 0)
475         pthread_cond_broadcast(&rwlock->can_read);
476 }