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
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 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.
28 * ntthread.c: Interface from Empire threads to Windows NT threads
30 * Known contributors to this file:
33 * Ron Koenderink, 2004-2005
37 * EMPTHREADs for Windows NT.
39 * Actually, threads for any Win32 platform, like Win95, Win98, WinCE,
40 * and whatever other toy OSs are in our future from Microsoft.
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.
52 #include <sys/types.h>
60 #include "empthread.h"
62 #define loc_MIN_THREAD_STACK 16384
64 /************************
69 /* The thread name, passed in at create time. */
71 /* The thread description, passed in at create time. */
74 /* True if this is the main line, and not a real thread. */
77 /* The user data passed in at create time. */
80 /* True if this thread has been killed. */
83 /* The entry function for the thread. */
84 void (*pfnEntry) (void *);
86 /* The system thread ID. */
87 unsigned long ulThreadID;
89 /* An Event sem that the thread will wait/sleep on. */
94 /************************
101 /* An exclusion semaphore for this sem. */
103 /* An Event sem that the thread(s) will sleep on. */
106 /* The count variable */
110 /* This is the thread exclusion/non-premption mutex. */
111 /* The running thread has this MUTEX, and all others are */
112 /* either blocked on it, or waiting for some OS response. */
113 static HANDLE hThreadMutex;
115 /* This is the thread startup event sem. */
116 /* We use this to lockstep when we are starting up threads. */
117 static HANDLE hThreadStartEvent;
119 /* This is an event used to wakeup the main thread */
120 /* to start the shutdown sequence. */
121 static HANDLE hShutdownEvent;
123 /* The Thread Local Storage index. We store the pThread pointer */
124 /* for each thread at this index. */
125 static DWORD dwTLSIndex;
127 /* The current running thread. */
128 static empth_t *pCurThread;
131 static unsigned long ulTickAtStart;
133 /* Pointer out to global context. "player". */
134 /* From empth_init parameter. */
135 static void **ppvUserData;
137 /* Global flags. From empth_init parameter. */
138 static int global_flags;
141 /************************
144 * Print out the current thread's status??
147 loc_debug(const char *pszFmt, ...)
150 unsigned long ulCurTick;
151 unsigned long ulRunTick;
152 unsigned long ulMs, ulSec, ulMin, ulHr;
153 empth_t *pThread = TlsGetValue(dwTLSIndex);
156 if ((global_flags & EMPTH_PRINT) != 0) {
158 /* Ticks are in milliseconds */
159 ulCurTick = GetTickCount();
161 ulRunTick = ulCurTick - ulTickAtStart;
162 ulMs = ulRunTick % 1000L;
163 ulSec = (ulRunTick / 1000L) % 60L;
164 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
165 ulHr = (ulRunTick / (60L * 60L * 1000L));
167 va_start(vaList, pszFmt);
168 vsprintf(buf, pszFmt, vaList);
172 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
173 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
175 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
176 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
182 /************************
186 loc_FreeThreadInfo(empth_t *pThread)
189 if (pThread->hThreadEvent)
190 CloseHandle(pThread->hThreadEvent);
191 memset(pThread, 0, sizeof(*pThread));
196 /************************
199 * This thread wants to run.
200 * When this function returns, the globals are set to this thread
201 * info, and the thread owns the MUTEX sem.
204 loc_RunThisThread(void)
206 empth_t *pThread = TlsGetValue(dwTLSIndex);
208 if (pThread->bKilled) {
209 if (!pThread->bMainThread) {
210 TlsSetValue(dwTLSIndex, NULL);
211 loc_FreeThreadInfo(pThread);
216 /* Get the MUTEX semaphore, wait forever. */
217 WaitForSingleObject(hThreadMutex, INFINITE);
220 /* Set the globals to this thread. */
221 *ppvUserData = pThread->pvUserData;
223 pCurThread = pThread;
225 /* Hmm, a problem, eh? */
226 logerror("RunThisThread, someone already running.");
230 /************************
231 * loc_BlockThisThread
233 * This thread was running. It no longer wants to.
236 loc_BlockThisThread(void)
238 empth_t *pThread = TlsGetValue(dwTLSIndex);
240 if (pCurThread == pThread) {
241 /* Reset the globals back to original */
246 /* Release the MUTEX */
247 ReleaseMutex(hThreadMutex);
249 /* Hmm, this thread was not the running one. */
250 logerror("BlockThisThread, not running.");
254 /************************
257 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
258 * System-Shutdown will initiate a shutdown.
259 * This is done by calling empth_request_shutdown()
262 loc_Exit_Handler(DWORD fdwCtrlType)
264 switch (fdwCtrlType) {
266 case CTRL_CLOSE_EVENT:
267 case CTRL_BREAK_EVENT:
268 case CTRL_LOGOFF_EVENT:
269 case CTRL_SHUTDOWN_EVENT:
270 empth_request_shutdown();
277 /************************
280 * This is the main line of each thread.
281 * This is really a static local func....
284 empth_threadMain(void *pvData)
288 empth_t *pThread = pvData;
294 /* Store pThread on this thread. */
295 TlsSetValue(dwTLSIndex, pvData);
297 /* Get the ID of the thread. */
298 pThread->ulThreadID = GetCurrentThreadId();
300 /* Signal that the thread has started. */
301 SetEvent(hThreadStartEvent);
303 /* seed the rand() function */
305 srand(now ^ (unsigned)pThread);
307 /* Switch to this thread context */
310 /* Run the thread. */
311 if (pThread->pfnEntry)
312 pThread->pfnEntry(pThread->pvUserData);
314 /* Kill the thread. */
318 /************************
321 * Initialize the thread environment.
323 * This is called from the program main line.
326 empth_init(void **ctx_ptr, int flags)
328 empth_t *pThread = NULL;
330 ulTickAtStart = GetTickCount();
331 ppvUserData = ctx_ptr;
332 global_flags = flags;
333 dwTLSIndex = TlsAlloc();
335 /* Create the thread mutex sem. */
336 /* Initally unowned. */
337 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
339 logerror("Failed to create mutex %lu", GetLastError());
343 /* Create the thread start event sem. */
344 /* Automatic state reset. */
345 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
346 if (!hThreadStartEvent) {
347 logerror("Failed to create start event %lu", GetLastError());
351 /* Create the shutdown event for the main thread. */
353 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
354 if (!hShutdownEvent) {
355 logerror("Failed to create shutdown event %lu", GetLastError());
358 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
360 /* Create the global Thread context. */
361 pThread = malloc(sizeof(*pThread));
363 logerror("not enough memory to create main thread.");
366 memset(pThread, 0, sizeof(*pThread));
368 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
369 strncpy(pThread->szDesc, "The main process",
370 sizeof(pThread->szDesc) - 1);
371 pThread->ulThreadID = GetCurrentThreadId();
372 pThread->bMainThread = TRUE;
374 TlsSetValue(dwTLSIndex, pThread);
376 /* Make this the running thread. */
379 logerror("NT pthreads initialized");
384 /************************
387 * Create a new thread.
389 * prio - priority, not particularly useful in our context.
390 * entry - entry point function for thread.
392 * flags - debug control.
393 * LWP_STACKCHECK - not needed
394 * name - name of the thread, for debug.
395 * desc - description of thread, for debug.
396 * ud - "user data". The "ctx_ptr" gets this value
397 * when the thread is active.
398 * It is also passed to the entry function...
401 empth_create(int prio, void (*entry)(void *), int size, int flags,
402 char *name, char *desc, void *ud)
404 empth_t *pThread = NULL;
406 loc_debug("creating new thread %s:%s", name, desc);
408 pThread = malloc(sizeof(*pThread));
410 logerror("not enough memory to create thread: %s (%s)",
414 memset(pThread, 0, sizeof(*pThread));
416 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
417 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
418 pThread->pvUserData = ud;
419 pThread->pfnEntry = entry;
420 pThread->bMainThread = FALSE;
422 /* Create thread event sem, auto reset. */
423 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
425 if (size < loc_MIN_THREAD_STACK)
426 size = loc_MIN_THREAD_STACK;
428 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
429 if (pThread->ulThreadID == -1) {
430 logerror("can not create thread: %s (%s): %s",
431 name, desc, strerror(errno));
435 loc_debug("new thread id is %ld", pThread->ulThreadID);
441 loc_FreeThreadInfo(pThread);
447 /************************
453 empth_t *pThread = TlsGetValue(dwTLSIndex);
458 /************************
464 empth_t *pThread = TlsGetValue(dwTLSIndex);
466 loc_debug("empth_exit");
467 loc_BlockThisThread();
469 TlsSetValue(dwTLSIndex, NULL);
470 loc_FreeThreadInfo(pThread);
474 /************************
477 * Yield processing to another thread.
482 loc_BlockThisThread();
486 /************************
489 * Kill off the thread.
492 empth_terminate(empth_t *pThread)
494 loc_debug("killing thread %s", pThread->szName);
495 pThread->bKilled = TRUE;
497 SetEvent(pThread->hThreadEvent);
500 /************************
503 * Do a select on the given file.
506 * This would be one of the main functions used within gen\io.c
509 empth_select(int fd, int flags)
511 WSAEVENT hEventObject[2];
512 empth_t *pThread = TlsGetValue(dwTLSIndex);
514 loc_debug("%s select on %d",
515 flags == EMPTH_FD_READ ? "read" : "write", fd);
516 loc_BlockThisThread();
518 hEventObject[0] = WSACreateEvent();
519 hEventObject[1] = pThread->hThreadEvent;
521 if (flags == EMPTH_FD_READ)
522 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
523 else if (flags == EMPTH_FD_WRITE)
524 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
526 logerror("bad flag %d passed to empth_select", flags);
530 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
532 WSAEventSelect(fd, hEventObject[0], 0);
534 WSACloseEvent(hEventObject[0]);
539 /************************
542 * Wake up the specified thread.
545 empth_wakeup(empth_t *pThread)
547 loc_debug("waking up thread %s", pThread->szName);
549 /* Let it run if it is blocked... */
550 SetEvent(pThread->hThreadEvent);
553 /************************
556 * Put the given thread to sleep...
559 empth_sleep(time_t until)
563 loc_BlockThisThread();
565 while ((lSec = until - time(0)) > 0) {
566 loc_debug("going to sleep %ld sec", lSec);
570 loc_debug("sleep done. Waiting to run.");
575 /************************
576 * empth_request_shutdown
578 * This wakes up empth_wait_for_signal() so shutdown can proceed.
579 * This is done by signalling hShutdownEvent.
582 empth_request_shutdown(void)
584 SetEvent(hShutdownEvent);
588 empth_wait_for_signal(void)
590 loc_BlockThisThread();
592 /* Get the MUTEX semaphore, wait the number of MS */
593 WaitForSingleObject(hShutdownEvent, INFINITE);
599 /************************
602 * Create a signalling semaphore.
605 empth_sem_create(char *name, int cnt)
609 pSem = malloc(sizeof(*pSem));
611 logerror("out of memory at %s:%d", __FILE__, __LINE__);
615 memset(pSem, 0, sizeof(pSem));
616 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
618 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
619 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
625 /************************
628 * Hit/signal the specified semaphore.
631 empth_sem_signal(empth_sem_t *pSem)
633 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
635 /* Wait for the Semaphore */
636 WaitForSingleObject(pSem->hMutex, INFINITE);
638 if (pSem->count++ < 0) {
639 SetEvent(pSem->hEvent);
642 ReleaseMutex(pSem->hMutex);
645 /************************
648 * Wait for the specified signal semaphore to be signaled.
651 empth_sem_wait(empth_sem_t *pSem)
653 empth_t *pThread = TlsGetValue(dwTLSIndex);
655 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
657 /* Remove the thread from the running state. */
658 loc_BlockThisThread();
660 /* Wait for the Semaphore */
661 WaitForSingleObject(pSem->hMutex, INFINITE);
662 if (--pSem->count < 0) {
663 loc_debug("blocking");
664 ReleaseMutex(pSem->hMutex);
666 WaitForSingleObject(pSem->hEvent, INFINITE);
668 loc_debug("waking up");
670 ReleaseMutex(pSem->hMutex);