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