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