]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
(loc_RunThread, empth_init, empth_threadMain, empth_yield)
[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
62 struct empth_t {
63     char *name;                 /* thread name */
64     char *desc;                 /* description */
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_sem_t {
72     pthread_mutex_t mtx_update; /* use it to update count */
73     int count;
74     char name[80];
75     pthread_mutex_t mtx_sem;
76     pthread_cond_t cnd_sem;
77 };
78
79 struct empth_rwlock_t {
80     char *name;
81     pthread_rwlock_t lock;
82 };
83
84 /* Thread-specific data key */
85 static pthread_key_t ctx_key;
86
87 /* Flags that were passed to empth_init() */
88 static int empth_flags;
89
90 /* Pointer to thread context variable */
91 static void **udata;
92
93 /*
94  * Non-preemption mutex.
95  * Empire code outside this file is only executed while holding this
96  * mutex.  This makes sure Empire code is never preempted by Empire
97  * code.
98  */
99 static pthread_mutex_t mtx_ctxsw;
100
101 static void empth_status(char *format, ...)
102     ATTRIBUTE((format (printf, 1, 2)));
103 static void empth_alarm(int sig);
104
105 static void *
106 empth_start(void *arg)
107 {
108     empth_t *ctx = arg;
109
110     ctx->id = pthread_self();
111     pthread_setspecific(ctx_key, ctx);
112     pthread_mutex_lock(&mtx_ctxsw);
113     *udata = ctx->ud;
114     ctx->ep(ctx->ud);
115     empth_exit();
116     return NULL;
117 }
118
119 static void
120 empth_status(char *format, ...)
121 {
122     va_list ap;
123     static struct timeval startTime;
124     struct timeval tv;
125     char buf[1024];
126     int sec, msec;
127     empth_t *a;
128
129     va_start(ap, format);
130     if (empth_flags & EMPTH_PRINT) {
131         if (startTime.tv_sec == 0)
132             gettimeofday(&startTime, 0);
133         gettimeofday(&tv, 0);
134         sec = tv.tv_sec - startTime.tv_sec;
135         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
136         if (msec < 0) {
137             sec++;
138             msec += 1000;
139         }
140         vsprintf(buf, format, ap);
141         a = empth_self();
142         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
143                a->name, buf);
144
145     }
146     va_end(ap);
147 }
148
149
150 int
151 empth_init(void **ctx_ptr, int flags)
152 {
153     empth_t *ctx;
154     sigset_t set;
155     struct sigaction act;
156
157     empth_flags = flags;
158     udata = ctx_ptr;
159
160     empth_init_signals();
161     sigemptyset(&set);
162     sigaddset(&set, SIGHUP);
163     sigaddset(&set, SIGINT);
164     sigaddset(&set, SIGTERM);
165     pthread_sigmask(SIG_BLOCK, &set, NULL);
166     act.sa_flags = 0;
167     sigemptyset(&act.sa_mask);
168     act.sa_handler = empth_alarm;
169     sigaction(SIGALRM, &act, NULL);
170
171     pthread_key_create(&ctx_key, NULL);
172     pthread_mutex_init(&mtx_ctxsw, NULL);
173
174     ctx = malloc(sizeof(empth_t));
175     if (!ctx) {
176         logerror("pthread init failed: not enough memory");
177         exit(1);
178     }
179     ctx->name = "Main";
180     ctx->desc = "empire main";
181     ctx->ep = 0;
182     ctx->ud = 0;
183     ctx->id = pthread_self();
184     ctx->state = 0;
185     pthread_setspecific(ctx_key, ctx);
186     pthread_mutex_lock(&mtx_ctxsw);
187     logerror("pthreads initialized");
188     return 0;
189 }
190
191
192 /*
193  * prio can be used for setting scheeduling policy but...
194  * it seems to be optional in POSIX threads and Solaris
195  * for example just ignores it.
196  * More then that priority is not needed even in lwp threads.
197  */
198 empth_t *
199 empth_create(int prio, void (*entry)(void *), int size, int flags,
200              char *name, char *desc, void *ud)
201 {
202     pthread_t t;
203     pthread_attr_t attr;
204     empth_t *ctx;
205     int eno;
206
207     empth_status("creating new thread %s:%s", name, desc);
208
209     ctx = malloc(sizeof(empth_t));
210     if (!ctx) {
211         logerror("not enough memory to create thread: %s (%s)",
212                  name, desc);
213         return NULL;
214     }
215     ctx->name = strdup(name);
216     ctx->desc = strdup(desc);
217     ctx->ud = ud;
218     ctx->state = 0;
219     ctx->ep = entry;
220
221     eno = pthread_attr_init(&attr);
222     if (eno) {
223         logerror("can not create thread attribute %s (%s): %s",
224                  name, desc, strerror(eno));
225         goto bad;
226     }
227     if (size < PTHREAD_STACK_MIN)
228         size = PTHREAD_STACK_MIN;
229     pthread_attr_setstacksize(&attr, size);
230     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
231
232     eno = pthread_create(&t, &attr, empth_start, ctx);
233     if (eno) {
234         logerror("can not create thread: %s (%s): %s",
235                  name, desc, strerror(eno));
236         goto bad;
237     }
238     empth_status("new thread id is %ld", (long)t);
239     empth_yield();
240     return ctx;
241
242   bad:
243     pthread_attr_destroy(&attr);
244     free(ctx);
245     return NULL;
246 }
247
248
249 static void
250 empth_restorectx(void)
251 {
252     empth_t *ctx_ptr;
253
254     ctx_ptr = pthread_getspecific(ctx_key);
255     *udata = ctx_ptr->ud;
256     if (ctx_ptr->state == EMPTH_KILLED) {
257         empth_status("i am dead");
258         empth_exit();
259     }
260     empth_status("context restored");
261 }
262
263 empth_t *
264 empth_self(void)
265 {
266     return pthread_getspecific(ctx_key);
267 }
268
269 void
270 empth_exit(void)
271 {
272     empth_status("empth_exit");
273     pthread_mutex_unlock(&mtx_ctxsw);
274     free(pthread_getspecific(ctx_key));
275     pthread_exit(0);
276 }
277
278 void
279 empth_yield(void)
280 {
281     pthread_mutex_unlock(&mtx_ctxsw);
282     pthread_mutex_lock(&mtx_ctxsw);
283     empth_restorectx();
284 }
285
286 void
287 empth_terminate(empth_t *a)
288 {
289     empth_status("killing thread %s", a->name);
290     a->state = EMPTH_KILLED;
291     pthread_kill(a->id, SIGALRM);
292 }
293
294 void
295 empth_select(int fd, int flags)
296 {
297
298     fd_set readmask;
299     fd_set writemask;
300     struct timeval tv;
301     int n;
302
303     pthread_mutex_unlock(&mtx_ctxsw);
304     empth_status("%s select on %d",
305                  flags == EMPTH_FD_READ ? "read" : "write", fd);
306     while (1) {
307         tv.tv_sec = 1000000;
308         tv.tv_usec = 0;
309
310         FD_ZERO(&readmask);
311         FD_ZERO(&writemask);
312
313         switch (flags) {
314         case EMPTH_FD_READ:
315             FD_SET(fd, &readmask);
316             break;
317         case EMPTH_FD_WRITE:
318             FD_SET(fd, &writemask);
319             break;
320         default:
321             logerror("bad flag %d passed to empth_select", flags);
322             empth_exit();
323         }
324
325         n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
326
327         if (n < 0) {
328             if (errno == EINTR) {
329                 /* go handle the signal */
330                 empth_status("select broken by signal");
331                 goto done;
332                 return;
333             }
334             /* strange but we dont get EINTR on select broken by signal */
335             empth_status("select failed (%s)", strerror(errno));
336             goto done;
337             return;
338         }
339
340         if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
341             empth_status("input ready");
342             break;
343         }
344         if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
345             empth_status("output ready");
346             break;
347         }
348     }
349
350   done:
351     pthread_mutex_lock(&mtx_ctxsw);
352     empth_restorectx();
353 }
354
355 static void
356 empth_alarm(int sig)
357 {
358     /*
359      * Nothing to do --- we handle this signal just to let
360      * empth_wakeup() interrupt system calls.
361      */
362     empth_status("got alarm signal");
363 }
364
365 void
366 empth_wakeup(empth_t *a)
367 {
368     empth_status("waking up thread %s", a->name);
369     pthread_kill(a->id, SIGALRM);
370 }
371
372 void
373 empth_sleep(time_t until)
374 {
375     struct timeval tv;
376
377     empth_status("going to sleep %ld sec", until - time(0));
378     pthread_mutex_unlock(&mtx_ctxsw);
379     tv.tv_sec = until - time(NULL);
380     tv.tv_usec = 0;
381     do {
382         select(0, NULL, NULL, NULL, &tv);
383     } while ((tv.tv_sec = until - time(NULL)) > 0);
384     empth_status("sleep done. Waiting for lock");
385     pthread_mutex_lock(&mtx_ctxsw);
386     empth_restorectx();
387 }
388
389 int
390 empth_wait_for_signal(void)
391 {
392     sigset_t set;
393     int sig, err;
394
395     sigemptyset(&set);
396     sigaddset(&set, SIGHUP);
397     sigaddset(&set, SIGINT);
398     sigaddset(&set, SIGTERM);
399     pthread_mutex_unlock(&mtx_ctxsw);
400     for (;;) {
401         empth_status("waiting for signals");
402         err = sigwait(&set, &sig);
403         if (CANT_HAPPEN(err)) {
404             sleep(60);
405             continue;
406         }
407         empth_status("got awaited signal %d", sig);
408         pthread_mutex_lock(&mtx_ctxsw);
409         empth_restorectx();
410         return sig;
411     }
412 }
413
414 empth_sem_t *
415 empth_sem_create(char *name, int cnt)
416 {
417     empth_sem_t *sm;
418
419     sm = malloc(sizeof(empth_sem_t));
420     if (!sm) {
421         logerror("out of memory at %s:%d", __FILE__, __LINE__);
422         return NULL;
423     }
424     strncpy(sm->name, name, sizeof(sm->name) - 1);
425     sm->count = cnt;
426     pthread_mutex_init(&sm->mtx_update, NULL);
427     pthread_mutex_init(&sm->mtx_sem, NULL);
428     pthread_cond_init(&sm->cnd_sem, NULL);
429     return sm;
430 }
431
432 void
433 empth_sem_signal(empth_sem_t *sm)
434 {
435     empth_status("signal on semaphore %s:%d", sm->name, sm->count);
436     pthread_mutex_lock(&sm->mtx_update);
437     if (sm->count++ < 0) {
438         pthread_mutex_unlock(&sm->mtx_update);
439         pthread_mutex_lock(&sm->mtx_sem);
440         pthread_cond_signal(&sm->cnd_sem);
441         pthread_mutex_unlock(&sm->mtx_sem);
442     } else
443         pthread_mutex_unlock(&sm->mtx_update);
444 }
445
446 void
447 empth_sem_wait(empth_sem_t *sm)
448 {
449     empth_status("wait on semaphore %s:%d", sm->name, sm->count);
450     pthread_mutex_lock(&sm->mtx_update);
451     if (--sm->count < 0) {
452         pthread_mutex_unlock(&sm->mtx_update);
453         empth_status("blocking");
454         pthread_mutex_unlock(&mtx_ctxsw);
455         pthread_mutex_lock(&sm->mtx_sem);
456         pthread_cond_wait(&sm->cnd_sem, &sm->mtx_sem);
457         empth_status("waking up");
458         pthread_mutex_unlock(&sm->mtx_sem);
459         pthread_mutex_lock(&mtx_ctxsw);
460         empth_restorectx();
461     } else
462         pthread_mutex_unlock(&sm->mtx_update);
463 }
464
465 empth_rwlock_t *
466 empth_rwlock_create(char *name)
467 {
468     empth_rwlock_t *rwlock;
469
470     rwlock = malloc(sizeof(*rwlock));
471     if (!rwlock)
472         return NULL;
473
474     if (pthread_rwlock_init(&rwlock->lock, NULL) != 0) {
475         free(rwlock);
476         return NULL;
477     }
478
479     rwlock->name = strdup(name);
480     return rwlock;
481 }
482
483 void
484 empth_rwlock_destroy(empth_rwlock_t *rwlock)
485 {
486     pthread_rwlock_destroy(&rwlock->lock);
487     free(rwlock);
488 }
489
490 void
491 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
492 {
493     pthread_mutex_unlock(&mtx_ctxsw);
494     pthread_rwlock_wrlock(&rwlock->lock);
495     pthread_mutex_lock(&mtx_ctxsw);
496     empth_restorectx();
497 }
498
499 void
500 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
501 {
502     pthread_mutex_unlock(&mtx_ctxsw);
503     pthread_rwlock_rdlock(&rwlock->lock);
504     pthread_mutex_lock(&mtx_ctxsw);
505     empth_restorectx();
506 }
507
508 void
509 empth_rwlock_unlock(empth_rwlock_t *rwlock)
510 {
511     pthread_rwlock_unlock(&rwlock->lock);
512 }