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