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