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