]> git.pond.sub.org Git - empserver/blob - src/lib/empthread/ntthread.c
Semaphores are no longer used, remove:
[empserver] / src / lib / empthread / ntthread.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2007, 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  *  ntthread.c: Interface from Empire threads to Windows NT threads
29  * 
30  *  Known contributors to this file:
31  *     Doug Hay, 1998
32  *     Steve McClure, 1998
33  *     Ron Koenderink, 2004-2007
34  */
35
36 /*
37  * EMPTHREADs for Windows NT.
38  *
39  * Actually, threads for any Win32 platform, like Win95, Win98, WinCE,
40  * and whatever other toy OSs are in our future from Microsoft.
41  *
42  * WIN32 has a full pre-emptive threading environment.  But Empire can
43  * not handle pre-emptive threading.  Thus, we will use the threads,
44  * but limit the preemption using a Mutex.
45  */
46
47 #include <config.h>
48
49 #include <errno.h>
50 #include <signal.h>
51 #include <stdio.h>
52 #include <sys/types.h>
53 #include <time.h>
54 #define WIN32
55 #include <winsock2.h>
56 #undef NS_ALL
57 #include <windows.h>
58 #include <process.h>
59 #include "misc.h"
60 #include "empthread.h"
61 #include "prototypes.h"
62
63 #define loc_MIN_THREAD_STACK  16384
64
65 /************************
66  * loc_Thread
67  */
68 struct loc_Thread {
69
70     /* The thread name, passed in at create time. */
71     char szName[17];
72
73     /* True if this is the main line, and not a real thread. */
74     BOOL bMainThread;
75
76     /* The user data passed in at create time. */
77     void *pvUserData;
78
79     /* True if this thread has been killed. */
80     BOOL bKilled;
81
82     /* The entry function for the thread. */
83     void (*pfnEntry) (void *);
84
85     /* The system thread ID. */
86     unsigned long ulThreadID;
87
88     /* An Mutex that the thread will wait/sleep on. */
89     HANDLE hThreadEvent;
90 };
91
92
93 /************************
94  * loc_RWLock
95  *
96  * Invariants
97  *      must hold at function call, return, sleep
98  *      and resume from sleep.
99  *
100  * any state:
101  *      nwrite >= 0
102  *      nread >= 0
103
104  * if unlocked:
105  *      can_read set
106  *      can_write set
107  *      nwrite == 0
108  *      nread == 0
109  *
110  * if read-locked without writers contending:
111  *      can_read set
112  *      can_write clear
113  *      nwrite == 0
114  *      nread > 0
115  *
116  * if read-locked with writers contending:
117  *      can_read clear
118  *      can_write clear
119  *      nwrite > 0    #writers blocked
120  *      nread > 0
121  *
122  * if write-locked:
123  *      can_read clear
124  *      can_write clear
125  *      nwrite > 0    #writers blocked + 1
126  *      nread == 0
127  *
128  * To ensure consistency, state normally changes only while the
129  * thread changing it holds hThreadMutex.
130  *
131  */
132 struct loc_RWLock {
133     char name[17];      /* The thread name, passed in at create time. */
134     HANDLE can_read;    /* Manual event -- allows read locks */
135     HANDLE can_write;   /* Auto-reset event -- allows write locks */
136     int nread;          /* number of active readers */
137     int nwrite;         /* total number of writers (active and waiting) */
138 };
139
140 /* This is the thread exclusion/non-premption mutex. */
141 /* The running thread has this MUTEX, and all others are */
142 /* either blocked on it, or waiting for some OS response. */
143 static HANDLE hThreadMutex;
144
145 /* This is the thread startup event. */
146 /* We use this to lockstep when we are starting up threads. */
147 static HANDLE hThreadStartEvent;
148
149 /* This is an event used to wakeup the main thread */
150 /* to start the shutdown sequence. */
151 static HANDLE hShutdownEvent;
152
153 /* The Thread Local Storage index.  We store the pThread pointer */
154 /* for each thread at this index. */
155 static DWORD dwTLSIndex;
156
157 /* The current running thread. */
158 static empth_t *pCurThread;
159
160 /* Ticks at start */
161 static unsigned long ulTickAtStart;
162
163 /* Pointer out to global context.  "player". */
164 /* From empth_init parameter. */
165 static void **ppvUserData;
166
167 /* Global flags.  From empth_init parameter. */
168 static int global_flags;
169
170
171 /************************
172  * loc_debug
173  *
174  * Print out the current thread's status??
175  */
176 static void
177 loc_debug(const char *pszFmt, ...)
178 {
179     va_list vaList;
180     unsigned long ulCurTick;
181     unsigned long ulRunTick;
182     unsigned long ulMs, ulSec, ulMin, ulHr;
183     empth_t *pThread = TlsGetValue(dwTLSIndex);
184     char buf[1024];
185
186     if ((global_flags & EMPTH_PRINT) != 0) {
187
188         /* Ticks are in milliseconds */
189         ulCurTick = GetTickCount();
190
191         ulRunTick = ulCurTick - ulTickAtStart;
192         ulMs = ulRunTick % 1000L;
193         ulSec = (ulRunTick / 1000L) % 60L;
194         ulMin = (ulRunTick / (60L * 1000L)) % 60L;
195         ulHr = (ulRunTick / (60L * 60L * 1000L));
196
197         va_start(vaList, pszFmt);
198         vsprintf(buf, pszFmt, vaList);
199         va_end(vaList);
200
201         if (pThread) {
202             printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
203                    ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
204         } else {
205             printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
206                    ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
207         }
208
209     }
210 }
211
212 /************************
213  * loc_FreeThreadInfo
214  */
215 static void
216 loc_FreeThreadInfo(empth_t *pThread)
217 {
218     if (pThread) {
219         if (pThread->hThreadEvent)
220             CloseHandle(pThread->hThreadEvent);
221         memset(pThread, 0, sizeof(*pThread));
222         free(pThread);
223     }
224 }
225
226 /************************
227  * loc_RunThisThread
228  *
229  * This thread wants to run.
230  * When this function returns, the globals are set to this thread
231  * info, and the thread owns the MUTEX.
232  */
233 static void
234 loc_RunThisThread(HANDLE hWaitObject)
235 {
236     HANDLE hWaitObjects[2];
237
238     empth_t *pThread = TlsGetValue(dwTLSIndex);
239
240     if (pThread->bKilled) {
241         if (!pThread->bMainThread) {
242             TlsSetValue(dwTLSIndex, NULL);
243             loc_FreeThreadInfo(pThread);
244             _endthread();
245         }
246     }
247
248     hWaitObjects[0] = hThreadMutex;
249     hWaitObjects[1] = hWaitObject;
250
251     WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
252                            TRUE, INFINITE);
253
254     if (!pCurThread) {
255         /* Set the globals to this thread. */
256         *ppvUserData = pThread->pvUserData;
257
258         pCurThread = pThread;
259     } else {
260         /* Hmm, a problem, eh? */
261         logerror("RunThisThread, someone already running.");
262     }
263 }
264
265 /************************
266  * loc_BlockThisThread
267  *
268  * This thread was running.  It no longer wants to.
269  */
270 static void
271 loc_BlockThisThread(void)
272 {
273     empth_t *pThread = TlsGetValue(dwTLSIndex);
274
275     if (pCurThread == pThread) {
276         /* Reset the globals back to original */
277
278         pCurThread = NULL;
279         *ppvUserData = NULL;
280
281         /* Release the MUTEX */
282         ReleaseMutex(hThreadMutex);
283     } else {
284         /* Hmm, this thread was not the running one. */
285         logerror("BlockThisThread, not running.");
286     }
287 }
288
289 /************************
290  * loc_Exit_Handler
291  *
292  * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
293  * System-Shutdown will initiate a shutdown.
294  * This is done by calling empth_request_shutdown()
295  */
296 static BOOL
297 loc_Exit_Handler(DWORD fdwCtrlType)
298 {
299     switch (fdwCtrlType) { 
300         case CTRL_C_EVENT:
301         case CTRL_CLOSE_EVENT:
302         case CTRL_BREAK_EVENT: 
303         case CTRL_LOGOFF_EVENT: 
304         case CTRL_SHUTDOWN_EVENT: 
305             empth_request_shutdown();
306             return TRUE;
307         default:
308             return FALSE;
309     }
310 }
311
312 /************************
313  * empth_threadMain
314  *
315  * This is the main line of each thread.
316  * This is really a static local func....
317  */
318 static void
319 empth_threadMain(void *pvData)
320 {
321     time_t now;
322
323     empth_t *pThread = pvData;
324
325     /* Out of here... */
326     if (!pvData)
327         return;
328
329     /* Store pThread on this thread. */
330     TlsSetValue(dwTLSIndex, pvData);
331
332     /* Get the ID of the thread. */
333     pThread->ulThreadID = GetCurrentThreadId();
334
335     /* Signal that the thread has started. */
336     SetEvent(hThreadStartEvent);
337
338     /* seed the rand() function */
339     time(&now);
340     srand(now ^ (unsigned)pThread);
341
342     /* Switch to this thread context */
343     loc_RunThisThread(NULL);
344
345     /* Run the thread. */
346     if (pThread->pfnEntry)
347         pThread->pfnEntry(pThread->pvUserData);
348
349     /* Kill the thread. */
350     empth_exit();
351 }
352
353 /************************
354  * empth_init
355  *
356  * Initialize the thread environment.
357  *
358  * This is called from the program main line.
359  */
360 int
361 empth_init(void **ctx_ptr, int flags)
362 {
363     empth_t *pThread = NULL;
364
365     ulTickAtStart = GetTickCount();
366     ppvUserData = ctx_ptr;
367     global_flags = flags;
368     dwTLSIndex = TlsAlloc();
369
370     /* Create the thread mutex. */
371     /* Initally unowned. */
372     hThreadMutex = CreateMutex(NULL, FALSE, NULL);
373     if (!hThreadMutex) {
374         logerror("Failed to create mutex %lu", GetLastError());
375         return 0;
376     }
377
378     /* Create the thread start event. */
379     /* Automatic state reset. */
380     hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
381     if (!hThreadStartEvent) {
382         logerror("Failed to create start event %lu", GetLastError());
383         return 0;
384     }
385
386     /* Create the shutdown event for the main thread. */
387     /* Manual reset */
388     hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
389     if (!hShutdownEvent) {
390         logerror("Failed to create shutdown event %lu", GetLastError());
391         return 0;
392     }
393     SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
394
395     /* Create the global Thread context. */
396     pThread = malloc(sizeof(*pThread));
397     if (!pThread) {
398         logerror("not enough memory to create main thread.");
399         return 0;
400     }
401     memset(pThread, 0, sizeof(*pThread));
402
403     strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
404     pThread->ulThreadID = GetCurrentThreadId();
405     pThread->bMainThread = TRUE;
406
407     TlsSetValue(dwTLSIndex, pThread);
408
409     /* Make this the running thread. */
410     loc_RunThisThread(NULL);
411
412     logerror("NT pthreads initialized");
413     return 0;
414 }
415
416
417 /************************
418  * empth_create
419  *
420  * Create a new thread.
421  *
422  * prio  - priority, not particularly useful in our context.
423  * entry - entry point function for thread.
424  * size  - stack size.
425  * flags - debug control.
426  *           LWP_STACKCHECK  - not needed
427  * name  - name of the thread, for debug.
428  * ud    - "user data".  The "ctx_ptr" gets this value
429  *         when the thread is active.
430  *         It is also passed to the entry function...
431  */
432 empth_t *
433 empth_create(int prio, void (*entry)(void *), int size, int flags,
434              char *name, void *ud)
435 {
436     empth_t *pThread = NULL;
437
438     loc_debug("creating new thread %s", name);
439
440     pThread = malloc(sizeof(*pThread));
441     if (!pThread) {
442         logerror("not enough memory to create thread %s", name);
443         return NULL;
444     }
445     memset(pThread, 0, sizeof(*pThread));
446
447     strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
448     pThread->pvUserData = ud;
449     pThread->pfnEntry = entry;
450     pThread->bMainThread = FALSE;
451
452     /* Create thread event, auto reset. */
453     pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
454
455     if (size < loc_MIN_THREAD_STACK)
456         size = loc_MIN_THREAD_STACK;
457
458     pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
459     if (pThread->ulThreadID == -1) {
460         logerror("can not create thread: %s: %s", name, strerror(errno));
461         goto bad;
462     }
463
464     loc_debug("new thread id is %ld", pThread->ulThreadID);
465     empth_yield();
466     return pThread;
467
468   bad:
469     if (pThread) {
470         loc_FreeThreadInfo(pThread);
471     }
472     return NULL;
473 }
474
475
476 /************************
477  * empth_self
478  */
479 empth_t *
480 empth_self(void)
481 {
482     empth_t *pThread = TlsGetValue(dwTLSIndex);
483
484     return pThread;
485 }
486
487 /************************
488  * empth_exit
489  */
490 void
491 empth_exit(void)
492 {
493     empth_t *pThread = TlsGetValue(dwTLSIndex);
494
495     loc_debug("empth_exit");
496     loc_BlockThisThread();
497
498     TlsSetValue(dwTLSIndex, NULL);
499     loc_FreeThreadInfo(pThread);
500     _endthread();
501 }
502
503 /************************
504  * empth_yield
505  *
506  * Yield processing to another thread.
507  */
508 void
509 empth_yield(void)
510 {
511     loc_BlockThisThread();
512     loc_RunThisThread(NULL);
513 }
514
515 /************************
516  * empth_terminate
517  *
518  * Kill off the thread.
519  */
520 void
521 empth_terminate(empth_t *pThread)
522 {
523     loc_debug("killing thread %s", pThread->szName);
524     pThread->bKilled = TRUE;
525
526     SetEvent(pThread->hThreadEvent);
527 }
528
529 /************************
530  * empth_select
531  *
532  * Do a select on the given file.
533  * Wait for IO on it.
534  *
535  * This would be one of the main functions used within gen\io.c
536  */
537 void
538 empth_select(int fd, int flags)
539 {
540     WSAEVENT hEventObject[2];
541     empth_t *pThread = TlsGetValue(dwTLSIndex);
542
543     loc_debug("%s select on %d",
544               flags == EMPTH_FD_READ ? "read" : "write", fd);
545     loc_BlockThisThread();
546
547     hEventObject[0] = WSACreateEvent();
548     hEventObject[1] = pThread->hThreadEvent;
549
550     if (flags == EMPTH_FD_READ)
551         WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
552     else if (flags == EMPTH_FD_WRITE)
553         WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
554     else {
555         logerror("bad flag %d passed to empth_select", flags);
556         empth_exit();
557     }
558
559     WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
560
561     WSAEventSelect(fd, hEventObject[0], 0);
562
563     WSACloseEvent(hEventObject[0]);
564
565     loc_RunThisThread(NULL);
566 }
567
568 /************************
569  * empth_wakeup
570  *
571  * Wake up the specified thread.
572  */
573 void
574 empth_wakeup(empth_t *pThread)
575 {
576     loc_debug("waking up thread %s", pThread->szName);
577
578     /* Let it run if it is blocked... */
579     SetEvent(pThread->hThreadEvent);
580 }
581
582 /************************
583  * empth_sleep
584  *
585  * Put the given thread to sleep...
586  */
587 int
588 empth_sleep(time_t until)
589 {
590     long lSec;
591     empth_t *pThread = TlsGetValue(dwTLSIndex);
592     int iReturn = 0;
593
594     if ((lSec = until - time(0)) > 0) {
595         loc_BlockThisThread();
596         loc_debug("going to sleep %ld sec", lSec);
597
598         if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
599             WAIT_TIMEOUT)
600             iReturn = -1;
601
602         loc_debug("sleep done. Waiting to run.");
603         loc_RunThisThread(NULL);
604     }
605     return iReturn;
606 }
607
608 /************************
609  * empth_request_shutdown
610  *
611  * This wakes up empth_wait_for_signal() so shutdown can proceed.
612  * This is done by signalling hShutdownEvent.
613  */
614 void
615 empth_request_shutdown(void)
616 {
617     SetEvent(hShutdownEvent);
618 }
619
620 int
621 empth_wait_for_signal(void)
622 {
623     loc_BlockThisThread();
624     loc_RunThisThread(hShutdownEvent);
625     return 0;
626 }
627
628 empth_rwlock_t *
629 empth_rwlock_create(char *name)
630 {
631     empth_rwlock_t *rwlock;
632
633     rwlock = malloc(sizeof(*rwlock));
634     if (!rwlock)
635         return NULL;
636
637     memset(rwlock, 0, sizeof(*rwlock));
638     strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
639
640     if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
641         logerror("rwlock_create: failed to create reader event %s at %s:%d",
642             name, __FILE__, __LINE__);
643         free(rwlock);
644         return NULL;
645     }
646
647     if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
648         logerror("rwlock_create: failed to create writer event %s at %s:%d",
649             name, __FILE__, __LINE__);
650         CloseHandle(rwlock->can_read);
651         free(rwlock);
652         return NULL;
653     }
654     return rwlock;
655 }
656
657 void
658 empth_rwlock_destroy(empth_rwlock_t *rwlock)
659 {
660     if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
661         return;
662     CloseHandle(rwlock->can_read);
663     CloseHandle(rwlock->can_write);
664     free(rwlock);
665 }
666
667 void
668 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
669 {
670     /* block any new readers */
671     ResetEvent(rwlock->can_read);
672     rwlock->nwrite++;
673     loc_BlockThisThread();
674     loc_RunThisThread(rwlock->can_write);
675     CANT_HAPPEN(rwlock->nread != 0);
676 }
677
678 void
679 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
680 {
681     loc_BlockThisThread();
682     loc_RunThisThread(rwlock->can_read);
683     ResetEvent(rwlock->can_write);
684     rwlock->nread++;
685 }
686
687 void
688 empth_rwlock_unlock(empth_rwlock_t *rwlock)
689 {
690     if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
691         return;
692    if (rwlock->nread) { /* holding read lock */
693         rwlock->nread--;
694         if (rwlock->nread == 0)
695             SetEvent(rwlock->can_write);
696     } else {
697         rwlock->nwrite--;
698         SetEvent(rwlock->can_write);
699     }
700     if (rwlock->nwrite == 0)
701         SetEvent(rwlock->can_read);
702 }