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