]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/pthread.c
Fix build for systems that don't provide POSIX.1-2001 by default
[empserver] / src / lib / empthread / pthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2020, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire 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 3 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, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  pthread.c: Interface from Empire threads to POSIX threads
28  *
29  *  Known contributors to this file:
30  *     Sasha Mikheev
31  *     Steve McClure, 1998
32  *     Markus Armbruster, 2005-2012
33  *     Ron Koenderink, 2007-2009
34  */
35
36 #include <config.h>
37
38 #include <errno.h>
39 #include <limits.h>
40 #include <pthread.h>
41 #include <signal.h>
42 #include <stdarg.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <sys/select.h>
47 #include <unistd.h>
48 #include "misc.h"
49 #include "empthread.h"
50 #include "file.h"
51 #include "prototypes.h"
52
53 struct empth_t {
54     char *name;                 /* thread name */
55     void *ud;                   /* user data */
56     int wakeup;
57     void (*ep)(void *);         /* entry point */
58     pthread_t id;               /* thread ID */
59 };
60
61 struct empth_rwlock_t {
62     /* Can't use pthread_rwlock_t, because it needn't prefer writers */
63     char *name;
64     int nread;                  /* #active readers */
65     int nwrite;                 /* total #writers (active and waiting) */
66     pthread_cond_t can_read;
67     pthread_cond_t can_write;
68 };
69
70 /* Thread-specific data key */
71 static pthread_key_t ctx_key;
72
73 /* Flags that were passed to empth_init() */
74 static int empth_flags;
75
76 /* Pointer to thread context variable */
77 static void **udata;
78
79 /*
80  * Non-preemption mutex.
81  * Empire code outside this file is only executed while holding this
82  * mutex.  This makes sure Empire code is never preempted by Empire
83  * code.
84  */
85 static pthread_mutex_t mtx_ctxsw;
86
87 static void empth_status(char *format, ...)
88     ATTRIBUTE((format (printf, 1, 2)));
89 static void empth_alarm(int sig);
90
91 static void *
92 empth_start(void *arg)
93 {
94     empth_t *ctx = arg;
95
96     ctx->id = pthread_self();
97     pthread_setspecific(ctx_key, ctx);
98     pthread_mutex_lock(&mtx_ctxsw);
99     *udata = ctx->ud;
100     ctx->ep(ctx->ud);
101     empth_exit();
102     return NULL;
103 }
104
105 static void
106 empth_status(char *format, ...)
107 {
108     va_list ap;
109     static struct timeval startTime;
110     struct timeval tv;
111     char buf[1024];
112     int sec, msec;
113     empth_t *a;
114
115     va_start(ap, format);
116     if (empth_flags & EMPTH_PRINT) {
117         if (startTime.tv_sec == 0)
118             gettimeofday(&startTime, 0);
119         gettimeofday(&tv, 0);
120         sec = tv.tv_sec - startTime.tv_sec;
121         msec = (tv.tv_usec - startTime.tv_usec) / 1000;
122         if (msec < 0) {
123             sec++;
124             msec += 1000;
125         }
126         vsprintf(buf, format, ap);
127         a = empth_self();
128         printf("%d:%02d.%03d %17s: %s\n", sec / 60, sec % 60, msec / 10,
129                a->name, buf);
130
131     }
132     va_end(ap);
133 }
134
135
136 int
137 empth_init(void **ctx_ptr, int flags)
138 {
139     empth_t *ctx;
140     sigset_t set;
141     struct sigaction act;
142
143     empth_flags = flags;
144     udata = ctx_ptr;
145
146     empth_init_signals();
147     sigemptyset(&set);
148     sigaddset(&set, SIGHUP);
149     sigaddset(&set, SIGINT);
150     sigaddset(&set, SIGTERM);
151     pthread_sigmask(SIG_BLOCK, &set, NULL);
152     act.sa_flags = 0;
153     sigemptyset(&act.sa_mask);
154     act.sa_handler = empth_alarm;
155     sigaction(SIGALRM, &act, NULL);
156
157     pthread_key_create(&ctx_key, NULL);
158     pthread_mutex_init(&mtx_ctxsw, NULL);
159
160     ctx = malloc(sizeof(empth_t));
161     if (!ctx) {
162         logerror("pthread init failed: not enough memory");
163         exit(1);
164     }
165     ctx->name = "Main";
166     ctx->ep = 0;
167     ctx->ud = 0;
168     ctx->id = pthread_self();
169     ctx->wakeup = 0;
170     pthread_setspecific(ctx_key, ctx);
171     pthread_mutex_lock(&mtx_ctxsw);
172     return 0;
173 }
174
175
176 empth_t *
177 empth_create(void (*entry)(void *), int size, int flags,
178              char *name, void *ud)
179 {
180     pthread_t t;
181     pthread_attr_t attr;
182     empth_t *ctx;
183     int eno;
184
185     empth_status("creating new thread %s", name);
186     ef_make_stale();
187
188     ctx = malloc(sizeof(empth_t));
189     if (!ctx) {
190         logerror("not enough memory to create thread %s", name);
191         return NULL;
192     }
193     ctx->name = strdup(name);
194     ctx->ud = ud;
195     ctx->wakeup = 0;
196     ctx->ep = entry;
197
198     eno = pthread_attr_init(&attr);
199     if (eno) {
200         logerror("can not create thread attribute %s: %s",
201                  name, strerror(eno));
202         goto bad;
203     }
204     if (size < PTHREAD_STACK_MIN)
205         size = PTHREAD_STACK_MIN;
206     pthread_attr_setstacksize(&attr, size);
207     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
208
209     eno = pthread_create(&t, &attr, empth_start, ctx);
210     if (eno) {
211         logerror("can not create thread: %s: %s", name, strerror(eno));
212         goto bad;
213     }
214     empth_status("new thread ID is %ld", (long)t);
215     empth_yield();
216     return ctx;
217
218   bad:
219     pthread_attr_destroy(&attr);
220     free(ctx);
221     return NULL;
222 }
223
224
225 static void
226 empth_restorectx(void)
227 {
228     empth_t *ctx_ptr;
229
230     ctx_ptr = pthread_getspecific(ctx_key);
231     *udata = ctx_ptr->ud;
232     ctx_ptr->wakeup = 0;
233     empth_status("context restored");
234 }
235
236 empth_t *
237 empth_self(void)
238 {
239     return udata ? pthread_getspecific(ctx_key) : NULL;
240 }
241
242 char *
243 empth_name(empth_t *thread)
244 {
245     return thread->name;
246 }
247
248 void
249 empth_set_name(empth_t *thread, char *name)
250 {
251     if (thread->name)
252         free(thread->name);
253     thread->name = strdup(name);
254 }
255
256 void
257 empth_exit(void)
258 {
259     empth_t *ctx = pthread_getspecific(ctx_key);
260
261     empth_status("empth_exit");
262     ef_make_stale();
263     pthread_mutex_unlock(&mtx_ctxsw);
264     free(ctx->name);
265     free(ctx);
266     pthread_exit(0);
267 }
268
269 void
270 empth_yield(void)
271 {
272     ef_make_stale();
273     pthread_mutex_unlock(&mtx_ctxsw);
274     pthread_mutex_lock(&mtx_ctxsw);
275     empth_restorectx();
276 }
277
278 int
279 empth_select(int fd, int flags, struct timeval *timeout)
280 {
281     fd_set readmask;
282     fd_set writemask;
283     struct timeval tv;
284     int n;
285     empth_t *ctx;
286     int res = 0;
287
288     if (CANT_HAPPEN(fd < 0 || fd >= FD_SETSIZE)) {
289         errno = EBADF;
290         return -1;
291     }
292
293     ef_make_stale();
294     pthread_mutex_unlock(&mtx_ctxsw);
295     empth_status("select on %d for %d", fd, flags);
296
297 again:
298     FD_ZERO(&readmask);
299     FD_ZERO(&writemask);
300     if (flags & EMPTH_FD_READ)
301         FD_SET(fd, &readmask);
302     if (flags & EMPTH_FD_WRITE)
303         FD_SET(fd, &writemask);
304
305     if (timeout)
306         tv = *timeout;
307     n = select(fd + 1, &readmask, &writemask, NULL, timeout ? &tv : NULL);
308     if (n < 0) {
309         ctx = pthread_getspecific(ctx_key);
310         if (ctx->wakeup) {
311             empth_status("select woken up");
312             res = 0;
313         } else if (errno == EINTR) {
314             empth_status("select broken by signal");
315             goto again;
316         } else {
317             empth_status("select failed (%s)", strerror(errno));
318             res = -1;
319         }
320     } else if (n == 0) {
321         empth_status("select timed out");
322         res = 0;
323     } else if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
324         empth_status("input ready");
325         res = 1;
326     } else if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
327         empth_status("output ready");
328         res = 1;
329     }
330
331     pthread_mutex_lock(&mtx_ctxsw);
332     empth_restorectx();
333     return res;
334 }
335
336 static void
337 empth_alarm(int sig)
338 {
339     /*
340      * Nothing to do --- we handle this signal just to let
341      * empth_wakeup() interrupt system calls.
342      */
343 }
344
345 void
346 empth_wakeup(empth_t *a)
347 {
348     empth_status("waking up thread %s", a->name);
349     a->wakeup = 1;
350     pthread_kill(a->id, SIGALRM);
351 }
352
353 int
354 empth_sleep(time_t until)
355 {
356     empth_t *ctx = pthread_getspecific(ctx_key);
357     time_t now;
358     struct timeval tv;
359     int res;
360
361     ef_make_stale();
362     pthread_mutex_unlock(&mtx_ctxsw);
363     do {
364         now = time(NULL);
365         tv.tv_sec = until >= now ? until - now : 0;
366         tv.tv_usec = 0;
367         empth_status("going to sleep %ld sec", (long)tv.tv_sec);
368         res = select(0, NULL, NULL, NULL, &tv);
369     } while (res < 0 && !ctx->wakeup);
370     empth_status("sleep done. Waiting for lock");
371     pthread_mutex_lock(&mtx_ctxsw);
372     empth_restorectx();
373     return res;
374 }
375
376 int
377 empth_wait_for_signal(void)
378 {
379     sigset_t set;
380     int sig, err;
381
382     ef_make_stale();
383     sigemptyset(&set);
384     sigaddset(&set, SIGHUP);
385     sigaddset(&set, SIGINT);
386     sigaddset(&set, SIGTERM);
387     pthread_mutex_unlock(&mtx_ctxsw);
388     for (;;) {
389         empth_status("waiting for signals");
390         err = sigwait(&set, &sig);
391         if (CANT_HAPPEN(err)) {
392             sleep(60);
393             continue;
394         }
395         empth_status("got awaited signal %d", sig);
396         pthread_mutex_lock(&mtx_ctxsw);
397         empth_restorectx();
398         return sig;
399     }
400 }
401
402 empth_rwlock_t *
403 empth_rwlock_create(char *name)
404 {
405     empth_rwlock_t *rwlock;
406
407     rwlock = malloc(sizeof(*rwlock));
408     if (!rwlock)
409         return NULL;
410
411     if (pthread_cond_init(&rwlock->can_read, NULL) != 0
412         || pthread_cond_init(&rwlock->can_write, NULL) != 0) {
413         free(rwlock);
414         return NULL;
415     }
416
417     rwlock->name = strdup(name);
418     rwlock->nread = rwlock->nwrite = 0;
419     return rwlock;
420 }
421
422 void
423 empth_rwlock_destroy(empth_rwlock_t *rwlock)
424 {
425     pthread_cond_destroy(&rwlock->can_read);
426     pthread_cond_destroy(&rwlock->can_write);
427     free(rwlock->name);
428     free(rwlock);
429 }
430
431 void
432 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
433 {
434     empth_status("wrlock %s %d %d",
435                  rwlock->name, rwlock->nread, rwlock->nwrite);
436     ef_make_stale();
437     rwlock->nwrite++;
438     while (rwlock->nread != 0 || rwlock->nwrite != 1) {
439         empth_status("waiting for wrlock %s", rwlock->name);
440         pthread_cond_wait(&rwlock->can_write, &mtx_ctxsw);
441         empth_status("got wrlock %s %d %d",
442                      rwlock->name, rwlock->nread, rwlock->nwrite);
443         empth_restorectx();
444     }
445 }
446
447 void
448 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
449 {
450     empth_status("rdlock %s %d %d",
451                  rwlock->name, rwlock->nread, rwlock->nwrite);
452     ef_make_stale();
453     while (rwlock->nwrite) {
454         empth_status("waiting for rdlock %s", rwlock->name);
455         pthread_cond_wait(&rwlock->can_read, &mtx_ctxsw);
456         empth_status("got rdlock %s %d %d",
457                      rwlock->name, rwlock->nread, rwlock->nwrite);
458         empth_restorectx();
459     }
460     rwlock->nread++;
461 }
462
463 void
464 empth_rwlock_unlock(empth_rwlock_t *rwlock)
465 {
466     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
467         return;
468     if (rwlock->nread) {        /* holding read lock */
469         if (!--rwlock->nread)
470             pthread_cond_signal(&rwlock->can_write);
471     } else {
472         rwlock->nwrite--;
473         pthread_cond_signal(&rwlock->can_write);
474     }
475     if (rwlock->nwrite == 0)
476         pthread_cond_broadcast(&rwlock->can_read);
477 }