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