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
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.
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.
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
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.
28 * ntthread.c: Interface from Empire threads to Windows NT threads
30 * Known contributors to this file:
36 * EMPTHREADs for Windows NT.
38 * Actually, threads for any Win32 platform, like Win95, Win98, WinCE,
39 * and whatever other toy OSs are in our future from Microsoft.
41 * WIN32 has a full pre-emptive threading environment. But Empire can
42 * not handle pre-emptive threading. Thus, we will use the threads,
43 * but limit the preemption using a Mutex semaphore.
48 #include <sys/types.h>
52 #include "empthread.h"
53 #include "prototypes.h"
55 #if defined(_WIN32) && defined(_EMPTH_WIN32)
62 #define loc_MIN_THREAD_STACK 16384
64 /************************
67 * The REAL empth_t thread structure.
68 * The external world only gets a void pointer to this.
70 typedef struct loc_Thread_t {
72 /* The thread name, passed in at create time. */
74 /* The thread description, passed in at create time. */
77 /* True if this is the main line, and not a real thread. */
80 /* The user data passed in at create time. */
83 /* True if this thread has been killed. */
86 /* The entry function for the thread. */
87 void (*pfnEntry) (void *);
89 /* The system thread ID. */
90 unsigned long ulThreadID;
92 /* An Event sem that the thread will wait/sleep on. */
97 /************************
100 * The REAL empth_sem_t structure.
101 * The external world only gets a void pointer to this.
103 typedef struct loc_Sem_t {
107 /* An exclusion semaphore for this sem. */
109 /* An Event sem that the thread(s) will sleep on. */
112 /* The count variable */
117 /* This is the thread exclusion/non-premption mutex. */
118 /* The running thread has this MUTEX, and all others are */
119 /* either blocked on it, or waiting for some OS response. */
122 /* This is the thread startup event sem. */
123 /* We use this to lockstep when we are starting up threads. */
124 HANDLE hThreadStartEvent;
126 /* This is an event used to wakeup the main thread */
127 /* to start the shutdown sequence. */
128 HANDLE hShutdownEvent;
130 /* The Thread Local Storage index. We store the pThread pointer */
131 /* for each thread at this index. */
134 /* The current running thread. */
135 loc_Thread_t *pCurThread;
138 unsigned long ulTickAtStart;
140 /* Pointer out to global context. "player". */
141 /* From empth_init parameter. */
144 /* Global flags. From empth_init parameter. */
149 /************************
152 * Print out the current thread's status??
155 loc_debug(const char *pszFmt, ...)
158 unsigned long ulCurTick;
159 unsigned long ulRunTick;
160 unsigned long ulMs, ulSec, ulMin, ulHr;
161 loc_Thread_t *pThread =
162 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
165 if ((loc_GVAR.flags & EMPTH_PRINT) != 0) {
167 /* Ticks are in milliseconds */
168 ulCurTick = GetTickCount();
170 ulRunTick = ulCurTick - loc_GVAR.ulTickAtStart;
171 ulMs = ulRunTick % 1000L;
172 ulSec = (ulRunTick / 1000L) % 60L;
173 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
174 ulHr = (ulRunTick / (60L * 60L * 1000L));
176 va_start(vaList, pszFmt);
177 vsprintf(buf, pszFmt, vaList);
181 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
182 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
184 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
185 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
191 /************************
196 loc_FreeThreadInfo(loc_Thread_t *pThread)
199 if (pThread->hThreadEvent)
200 CloseHandle(pThread->hThreadEvent);
201 memset(pThread, 0, sizeof(*pThread));
206 /************************
209 * This thread wants to run.
210 * When this function returns, the globals are set to this thread
211 * info, and the thread owns the MUTEX sem.
216 loc_Thread_t *pThread =
217 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
219 if (pThread->bKilled) {
220 if (!pThread->bMainThread) {
221 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
222 loc_FreeThreadInfo(pThread);
227 /* Get the MUTEX semaphore, wait forever. */
228 WaitForSingleObject(loc_GVAR.hThreadMutex, INFINITE);
230 if (!loc_GVAR.pCurThread) {
231 /* Set the globals to this thread. */
232 *loc_GVAR.ppvUserData = pThread->pvUserData;
234 loc_GVAR.pCurThread = pThread;
236 /* Hmm, a problem, eh? */
237 logerror("RunThisThread, someone already running.");
241 /************************
242 * loc_BlockThisThread
244 * This thread was running. It no longer wants to.
247 loc_BlockThisThread()
249 loc_Thread_t *pThread =
250 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
252 if (loc_GVAR.pCurThread == pThread) {
253 /* Reset the globals back to original */
255 loc_GVAR.pCurThread = NULL;
256 *loc_GVAR.ppvUserData = NULL;
258 /* Release the MUTEX */
259 ReleaseMutex(loc_GVAR.hThreadMutex);
261 /* Hmm, this thread was not the running one. */
262 logerror("BlockThisThread, not running.");
266 /************************
269 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
270 * System-Shutdown will initiate a shutdown.
271 * This is done by calling empth_request_shutdown()
274 loc_Exit_Handler(DWORD fdwCtrlType)
279 case CTRL_CLOSE_EVENT:
280 case CTRL_BREAK_EVENT:
281 case CTRL_LOGOFF_EVENT:
282 case CTRL_SHUTDOWN_EVENT:
283 empth_request_shutdown();
290 /************************
291 * empth_request_shutdown
293 * This wakes up the main thread so shutdown can proceed.
294 * This is done by signalling hShutdownEvent.
297 empth_request_shutdown(void)
299 SetEvent(loc_GVAR.hShutdownEvent);
302 /************************
303 * loc_BlockMainThread
305 * This blocks up the main thread. loc_WakeupMainThread() is used
306 * wakeup the main so shutdown can proceed.
309 loc_BlockMainThread(void)
311 /* Get the MUTEX semaphore, wait the number of MS */
312 WaitForSingleObject(loc_GVAR.hShutdownEvent, INFINITE);
315 /************************
318 * This is the main line of each thread.
319 * This is really a static local func....
322 empth_threadMain(void *pvData)
326 loc_Thread_t *pThread = (loc_Thread_t *)pvData;
332 /* Store pThread on this thread. */
333 TlsSetValue(loc_GVAR.dwTLSIndex, pvData);
335 /* Get the ID of the thread. */
336 pThread->ulThreadID = GetCurrentThreadId();
338 /* Signal that the thread has started. */
339 SetEvent(loc_GVAR.hThreadStartEvent);
341 /* seed the rand() function */
343 srand(now ^ (unsigned int)pThread);
345 /* Switch to this thread context */
348 /* Run the thread. */
349 if (pThread->pfnEntry)
350 pThread->pfnEntry(pThread->pvUserData);
352 /* Kill the thread. */
356 /************************
359 * Initialize the thread environment.
361 * This is called from the program main line.
364 empth_init(void **ctx_ptr, int flags)
366 loc_Thread_t *pThread = NULL;
368 loc_GVAR.ulTickAtStart = GetTickCount();
369 loc_GVAR.ppvUserData = ctx_ptr;
370 loc_GVAR.flags = flags;
371 loc_GVAR.dwTLSIndex = TlsAlloc();
373 /* Create the thread mutex sem. */
374 /* Initally unowned. */
375 loc_GVAR.hThreadMutex = CreateMutex(NULL, FALSE, NULL);
376 if (!loc_GVAR.hThreadMutex) {
377 logerror("Failed to create mutex %d", GetLastError());
381 /* Create the thread start event sem. */
382 /* Automatic state reset. */
383 loc_GVAR.hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
384 if (!loc_GVAR.hThreadStartEvent) {
385 logerror("Failed to create start event %d", GetLastError());
389 /* Create the shutdown event for the main thread. */
391 loc_GVAR.hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
392 if (!loc_GVAR.hShutdownEvent) {
393 logerror("Failed to create shutdown event %d", GetLastError());
396 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
398 /* Create the global Thread context. */
399 pThread = malloc(sizeof(*pThread));
401 logerror("not enough memory to create main thread.");
404 memset(pThread, 0, sizeof(*pThread));
406 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
407 strncpy(pThread->szDesc, "The main process",
408 sizeof(pThread->szDesc) - 1);
409 pThread->ulThreadID = GetCurrentThreadId();
410 pThread->bMainThread = TRUE;
412 TlsSetValue(loc_GVAR.dwTLSIndex, pThread);
414 /* Make this the running thread. */
417 logerror("NT pthreads initialized");
422 /************************
425 * Create a new thread.
427 * prio - priority, not particularly useful in our context.
428 * entry - entry point function for thread.
430 * flags - debug control.
431 * LWP_STACKCHECK - not needed
432 * name - name of the thread, for debug.
433 * desc - description of thread, for debug.
434 * ud - "user data". The "ctx_ptr" gets this value
435 * when the thread is active.
436 * It is also passed to the entry function...
439 empth_create(int prio, void (*entry)(void *), int size, int flags,
440 char *name, char *desc, void *ud)
442 loc_Thread_t *pThread = NULL;
444 loc_debug("creating new thread %s:%s", name, desc);
446 pThread = malloc(sizeof(*pThread));
448 logerror("not enough memory to create thread: %s (%s)", name,
452 memset(pThread, 0, sizeof(*pThread));
454 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
455 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
456 pThread->pvUserData = ud;
457 pThread->pfnEntry = entry;
458 pThread->bMainThread = FALSE;
460 /* Create thread event sem, auto reset. */
461 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
463 if (size < loc_MIN_THREAD_STACK)
464 size = loc_MIN_THREAD_STACK;
466 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
467 if (pThread->ulThreadID == -1) {
468 logerror("can not create thread: %s (%s): %s", name, desc,
473 loc_debug("new thread id is %ld", pThread->ulThreadID);
478 loc_FreeThreadInfo(pThread);
484 /************************
490 loc_Thread_t *pThread =
491 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
496 /************************
502 loc_Thread_t *pThread =
503 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
505 loc_BlockThisThread();
507 loc_debug("empth_exit");
509 if (pThread->bMainThread) {
510 loc_BlockMainThread();
514 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
515 loc_FreeThreadInfo(pThread);
520 /************************
523 * Yield processing to another thread.
528 loc_BlockThisThread();
532 /************************
535 * Kill off the thread.
538 empth_terminate(empth_t *a)
540 loc_Thread_t *pThread = (loc_Thread_t *)a;
542 loc_debug("killing thread %s", pThread->szName);
543 pThread->bKilled = TRUE;
545 SetEvent(pThread->hThreadEvent);
548 /************************
551 * Do a select on the given file.
554 * This would be one of the main functions used within gen\io.c
557 empth_select(int fd, int flags)
559 WSAEVENT hEventObject[2];
560 loc_Thread_t *pThread =
561 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
563 loc_debug("%s select on %d",
564 flags == EMPTH_FD_READ ? "read" : "write", fd);
565 loc_BlockThisThread();
567 hEventObject[0] = WSACreateEvent();
568 hEventObject[1] = pThread->hThreadEvent;
570 if (flags == EMPTH_FD_READ)
571 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
572 else if (flags == EMPTH_FD_WRITE)
573 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
575 logerror("bad flag %d passed to empth_select", flags);
579 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
581 WSAEventSelect(fd, hEventObject[0], 0);
583 WSACloseEvent(hEventObject[0]);
588 /************************
594 loc_Thread_t *pThread =
595 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
597 loc_debug("got alarm signal %d", sig);
599 /* Let it run if it is blocked like... */
600 SetEvent(pThread->hThreadEvent);
603 /************************
606 * Wake up the specified thread.
609 empth_wakeup(empth_t *a)
611 loc_Thread_t *pThread = (loc_Thread_t *)a;
613 loc_debug("waking up thread %s", pThread->szName);
615 /* Let it run if it is blocked... */
616 SetEvent(pThread->hThreadEvent);
619 /************************
622 * Put the given thread to sleep...
625 empth_sleep(time_t until)
629 loc_BlockThisThread();
631 while ((lSec = until - time(0)) > 0) {
632 loc_debug("going to sleep %ld sec", lSec);
636 loc_debug("sleep done. Waiting to run.");
642 /************************
645 * Create a signalling semaphore.
648 empth_sem_create(char *name, int cnt)
652 pSem = malloc(sizeof(*pSem));
654 logerror("out of memory at %s:%d", __FILE__, __LINE__);
658 memset(pSem, 0, sizeof(pSem));
659 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
661 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
662 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
668 /************************
671 * Hit/signal the specified semaphore.
674 empth_sem_signal(empth_sem_t *sm)
676 loc_Sem_t *pSem = sm;
678 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
680 /* Wait for the Semaphore */
681 WaitForSingleObject(pSem->hMutex, INFINITE);
683 if (pSem->count++ < 0) {
684 SetEvent(pSem->hEvent);
687 ReleaseMutex(pSem->hMutex);
690 /************************
693 * Wait for the specified signal semaphore to be signaled.
696 empth_sem_wait(empth_sem_t *sm)
698 loc_Thread_t *pThread =
699 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
700 loc_Sem_t *pSem = sm;
702 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
704 /* Remove the thread from the running state. */
705 loc_BlockThisThread();
707 /* Wait for the Semaphore */
708 WaitForSingleObject(pSem->hMutex, INFINITE);
709 if (--pSem->count < 0) {
710 loc_debug("blocking");
711 ReleaseMutex(pSem->hMutex);
713 WaitForSingleObject(pSem->hEvent, INFINITE);
715 loc_debug("waking up");
717 ReleaseMutex(pSem->hMutex);