]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
(empth_create): LWP yields, and it's the reference implementation.
[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
34  */
35
36 #include <config.h>
37
38 #include <stdio.h>
39 #if !defined(_WIN32)
40 #include <sys/time.h>
41 #include <unistd.h>
42 #endif
43 #include <sys/types.h>
44 #include <signal.h>
45 #include <errno.h>
46 #include <string.h>
47 #include <limits.h>
48
49 #include "misc.h"
50 #include "empthread.h"
51 #include "prototypes.h"
52
53 #include <stdarg.h>
54
55 #define EMPTH_KILLED  1
56
57 struct empth_t {
58     char *name;                 /* thread name */
59     char *desc;                 /* description */
60     void *ud;                   /* user data */
61     int state;                  /* my state */
62     void (*ep)(void *);         /* entry point */
63     pthread_t id;               /* thread id */
64 };
65
66 struct empth_sem_t {
67     pthread_mutex_t mtx_update; /* use it to update count */
68     int count;
69     char name[80];
70     pthread_mutex_t mtx_sem;
71     pthread_cond_t cnd_sem;
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, ...) ATTRIBUTE((format (printf, 1, 2)));
92 static void empth_alarm(int sig);
93
94 static void *
95 empth_start(void *arg)
96 {
97     empth_t *ctx = arg;
98     struct sigaction act;
99
100     /* actually it should inherit all this from main but... */
101     act.sa_flags = 0;
102     sigemptyset(&act.sa_mask);
103     act.sa_handler = shutdwn;
104     sigaction(SIGTERM, &act, NULL);
105     sigaction(SIGINT, &act, NULL);
106     act.sa_handler = panic;
107     sigaction(SIGBUS, &act, NULL);
108     sigaction(SIGSEGV, &act, NULL);
109     sigaction(SIGILL, &act, NULL);
110     sigaction(SIGFPE, &act, NULL);
111     act.sa_handler = SIG_IGN;
112     sigaction(SIGPIPE, &act, NULL);
113
114     act.sa_handler = empth_alarm;
115     sigaction(SIGALRM, &act, NULL);
116
117     ctx->id = pthread_self();
118     pthread_setspecific(ctx_key, ctx);
119     pthread_mutex_lock(&mtx_ctxsw);
120     *udata = ctx->ud;
121     ctx->ep(ctx->ud);
122     empth_exit();
123     return NULL;
124 }
125
126 static void
127 empth_status(char *format, ...)
128 {
129     va_list ap;
130     static struct timeval startTime;
131     struct timeval tv;
132     char buf[1024];
133     int sec, msec;
134     empth_t *a;
135
136     va_start(ap, format);
137     if (empth_flags & EMPTH_PRINT) {
138         if (startTime.tv_sec == 0)
139             gettimeofday(&startTime, 0);
140         gettimeofday(&tv, 0);
141         sec = tv.tv_sec - startTime.tv_sec;
142         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
143         if (msec < 0) {
144             sec++;
145             msec += 1000;
146         }
147         vsprintf(buf, format, ap);
148         a = empth_self();
149         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
150                a->name, buf);
151
152     }
153     va_end(ap);
154 }
155
156
157 int
158 empth_init(void **ctx_ptr, int flags)
159 {
160     empth_t *ctx;
161     struct sigaction act;
162
163
164     pthread_key_create(&ctx_key, NULL);
165     pthread_mutex_init(&mtx_ctxsw, NULL);
166
167     act.sa_flags = 0;
168     sigemptyset(&act.sa_mask);
169     act.sa_handler = empth_alarm;
170     sigaction(SIGALRM, &act, NULL);
171
172     udata = ctx_ptr;
173     ctx = malloc(sizeof(empth_t));
174     if (!ctx) {
175         logerror("pthread init failed: not enough memory");
176         exit(1);
177     }
178     ctx->name = "Main";
179     ctx->desc = "empire main";
180     ctx->ep = 0;
181     ctx->ud = 0;
182     ctx->id = pthread_self();
183     ctx->state = 0;
184     pthread_setspecific(ctx_key, ctx);
185     pthread_mutex_lock(&mtx_ctxsw);
186     empth_flags = flags;
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)", name,
212                  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", name, desc,
224                  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", name, desc,
235                  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_t *ctx_ptr;
273
274     pthread_mutex_unlock(&mtx_ctxsw);
275     empth_status("empth_exit");
276     ctx_ptr = pthread_getspecific(ctx_key);
277     /* We want to leave the main thread around forever, until it's time
278        for it to die for real (in a shutdown) */
279     if (!strcmp(ctx_ptr->name, "Main")) {
280         while (1) {
281             sleep(60);
282         }
283     }
284
285     free(ctx_ptr);
286     pthread_exit(0);
287 }
288
289 void
290 empth_yield(void)
291 {
292     pthread_mutex_unlock(&mtx_ctxsw);
293     pthread_mutex_lock(&mtx_ctxsw);
294     empth_restorectx();
295 }
296
297 void
298 empth_terminate(empth_t *a)
299 {
300     empth_status("killing thread %s", a->name);
301     a->state = EMPTH_KILLED;
302     pthread_kill(a->id, SIGALRM);
303 }
304
305 void
306 empth_select(int fd, int flags)
307 {
308
309     fd_set readmask;
310     fd_set writemask;
311     struct timeval tv;
312     int n;
313
314     pthread_mutex_unlock(&mtx_ctxsw);
315     empth_status("%s select on %d",
316                  flags == EMPTH_FD_READ ? "read" : "write", fd);
317     while (1) {
318         tv.tv_sec = 1000000;
319         tv.tv_usec = 0;
320
321         FD_ZERO(&readmask);
322         FD_ZERO(&writemask);
323
324         switch (flags) {
325         case EMPTH_FD_READ:
326             FD_SET(fd, &readmask);
327             break;
328         case EMPTH_FD_WRITE:
329             FD_SET(fd, &writemask);
330             break;
331         default:
332             logerror("bad flag %d passed to empth_select", flags);
333             empth_exit();
334         }
335
336         n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
337
338         if (n < 0) {
339             if (errno == EINTR) {
340                 /* go handle the signal */
341                 empth_status("select broken by signal");
342                 goto done;
343                 return;
344             }
345             /* strange but we dont get EINTR on select broken by signal */
346             empth_status("select failed (%s)", strerror(errno));
347             goto done;
348             return;
349         }
350
351         if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
352             empth_status("input ready");
353             break;
354         }
355         if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
356             empth_status("output ready");
357             break;
358         }
359     }
360
361   done:
362     pthread_mutex_lock(&mtx_ctxsw);
363     empth_restorectx();
364
365 }
366
367
368 static void
369 empth_alarm(int sig)
370 {
371     struct sigaction act;
372     empth_status("got alarm signal");
373 #ifdef SA_RESTART
374     act.sa_flags &= ~SA_RESTART;
375 #endif
376     sigemptyset(&act.sa_mask);
377     act.sa_handler = empth_alarm;
378     sigaction(SIGALRM, &act, NULL);
379 }
380
381 void
382 empth_wakeup(empth_t *a)
383 {
384     empth_status("waking up thread %s", a->name);
385     pthread_kill(a->id, SIGALRM);
386     empth_status("waiting for it to run");
387 }
388
389 void
390 empth_sleep(time_t until)
391 {
392     struct timeval tv;
393
394     empth_status("going to sleep %ld sec", until - time(0));
395     pthread_mutex_unlock(&mtx_ctxsw);
396     tv.tv_sec = until - time(NULL);
397     tv.tv_usec = 0;
398     do {
399         select(0, NULL, NULL, NULL, &tv);
400     } while ((tv.tv_sec = until - time(NULL)) > 0);
401     empth_status("sleep done. Waiting for lock");
402     pthread_mutex_lock(&mtx_ctxsw);
403     empth_restorectx();
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 }