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