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.
50 #include <sys/types.h>
54 #include "empthread.h"
55 #include "prototypes.h"
63 #define loc_MIN_THREAD_STACK 16384
65 /************************
70 /* The thread name, passed in at create time. */
72 /* The thread description, passed in at create time. */
75 /* True if this is the main line, and not a real thread. */
78 /* The user data passed in at create time. */
81 /* True if this thread has been killed. */
84 /* The entry function for the thread. */
85 void (*pfnEntry) (void *);
87 /* The system thread ID. */
88 unsigned long ulThreadID;
90 /* An Event sem that the thread will wait/sleep on. */
95 /************************
102 /* An exclusion semaphore for this sem. */
104 /* An Event sem that the thread(s) will sleep on. */
107 /* The count variable */
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;
116 /* This is the thread startup event sem. */
117 /* We use this to lockstep when we are starting up threads. */
118 static HANDLE hThreadStartEvent;
120 /* This is an event used to wakeup the main thread */
121 /* to start the shutdown sequence. */
122 static HANDLE hShutdownEvent;
124 /* The Thread Local Storage index. We store the pThread pointer */
125 /* for each thread at this index. */
126 static DWORD dwTLSIndex;
128 /* The current running thread. */
129 static empth_t *pCurThread;
132 static unsigned long ulTickAtStart;
134 /* Pointer out to global context. "player". */
135 /* From empth_init parameter. */
136 static void **ppvUserData;
138 /* Global flags. From empth_init parameter. */
139 static int global_flags;
142 /************************
145 * Print out the current thread's status??
148 loc_debug(const char *pszFmt, ...)
151 unsigned long ulCurTick;
152 unsigned long ulRunTick;
153 unsigned long ulMs, ulSec, ulMin, ulHr;
154 empth_t *pThread = TlsGetValue(dwTLSIndex);
157 if ((global_flags & EMPTH_PRINT) != 0) {
159 /* Ticks are in milliseconds */
160 ulCurTick = GetTickCount();
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));
168 va_start(vaList, pszFmt);
169 vsprintf(buf, pszFmt, vaList);
173 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
174 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
176 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
177 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
183 /************************
188 loc_FreeThreadInfo(empth_t *pThread)
191 if (pThread->hThreadEvent)
192 CloseHandle(pThread->hThreadEvent);
193 memset(pThread, 0, sizeof(*pThread));
198 /************************
201 * This thread wants to run.
202 * When this function returns, the globals are set to this thread
203 * info, and the thread owns the MUTEX sem.
208 empth_t *pThread = TlsGetValue(dwTLSIndex);
210 if (pThread->bKilled) {
211 if (!pThread->bMainThread) {
212 TlsSetValue(dwTLSIndex, NULL);
213 loc_FreeThreadInfo(pThread);
218 /* Get the MUTEX semaphore, wait forever. */
219 WaitForSingleObject(hThreadMutex, INFINITE);
222 /* Set the globals to this thread. */
223 *ppvUserData = pThread->pvUserData;
225 pCurThread = pThread;
227 /* Hmm, a problem, eh? */
228 logerror("RunThisThread, someone already running.");
232 /************************
233 * loc_BlockThisThread
235 * This thread was running. It no longer wants to.
238 loc_BlockThisThread()
240 empth_t *pThread = TlsGetValue(dwTLSIndex);
242 if (pCurThread == pThread) {
243 /* Reset the globals back to original */
248 /* Release the MUTEX */
249 ReleaseMutex(hThreadMutex);
251 /* Hmm, this thread was not the running one. */
252 logerror("BlockThisThread, not running.");
256 /************************
259 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
260 * System-Shutdown will initiate a shutdown.
261 * This is done by calling empth_request_shutdown()
264 loc_Exit_Handler(DWORD fdwCtrlType)
269 case CTRL_CLOSE_EVENT:
270 case CTRL_BREAK_EVENT:
271 case CTRL_LOGOFF_EVENT:
272 case CTRL_SHUTDOWN_EVENT:
273 empth_request_shutdown();
280 /************************
281 * empth_request_shutdown
283 * This wakes up the main thread so shutdown can proceed.
284 * This is done by signalling hShutdownEvent.
287 empth_request_shutdown(void)
289 SetEvent(hShutdownEvent);
292 /************************
293 * loc_BlockMainThread
295 * This blocks up the main thread. loc_WakeupMainThread() is used
296 * wakeup the main so shutdown can proceed.
299 loc_BlockMainThread(void)
301 /* Get the MUTEX semaphore, wait the number of MS */
302 WaitForSingleObject(hShutdownEvent, INFINITE);
305 /************************
308 * This is the main line of each thread.
309 * This is really a static local func....
312 empth_threadMain(void *pvData)
316 empth_t *pThread = pvData;
322 /* Store pThread on this thread. */
323 TlsSetValue(dwTLSIndex, pvData);
325 /* Get the ID of the thread. */
326 pThread->ulThreadID = GetCurrentThreadId();
328 /* Signal that the thread has started. */
329 SetEvent(hThreadStartEvent);
331 /* seed the rand() function */
333 srand(now ^ (unsigned int)pThread);
335 /* Switch to this thread context */
338 /* Run the thread. */
339 if (pThread->pfnEntry)
340 pThread->pfnEntry(pThread->pvUserData);
342 /* Kill the thread. */
346 /************************
349 * Initialize the thread environment.
351 * This is called from the program main line.
354 empth_init(void **ctx_ptr, int flags)
356 empth_t *pThread = NULL;
358 ulTickAtStart = GetTickCount();
359 ppvUserData = ctx_ptr;
360 global_flags = flags;
361 dwTLSIndex = TlsAlloc();
363 /* Create the thread mutex sem. */
364 /* Initally unowned. */
365 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
367 logerror("Failed to create mutex %d", GetLastError());
371 /* Create the thread start event sem. */
372 /* Automatic state reset. */
373 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
374 if (!hThreadStartEvent) {
375 logerror("Failed to create start event %d", GetLastError());
379 /* Create the shutdown event for the main thread. */
381 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
382 if (!hShutdownEvent) {
383 logerror("Failed to create shutdown event %d", GetLastError());
386 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
388 /* Create the global Thread context. */
389 pThread = malloc(sizeof(*pThread));
391 logerror("not enough memory to create main thread.");
394 memset(pThread, 0, sizeof(*pThread));
396 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
397 strncpy(pThread->szDesc, "The main process",
398 sizeof(pThread->szDesc) - 1);
399 pThread->ulThreadID = GetCurrentThreadId();
400 pThread->bMainThread = TRUE;
402 TlsSetValue(dwTLSIndex, pThread);
404 /* Make this the running thread. */
407 logerror("NT pthreads initialized");
412 /************************
415 * Create a new thread.
417 * prio - priority, not particularly useful in our context.
418 * entry - entry point function for thread.
420 * flags - debug control.
421 * LWP_STACKCHECK - not needed
422 * name - name of the thread, for debug.
423 * desc - description of thread, for debug.
424 * ud - "user data". The "ctx_ptr" gets this value
425 * when the thread is active.
426 * It is also passed to the entry function...
429 empth_create(int prio, void (*entry)(void *), int size, int flags,
430 char *name, char *desc, void *ud)
432 empth_t *pThread = NULL;
434 loc_debug("creating new thread %s:%s", name, desc);
436 pThread = malloc(sizeof(*pThread));
438 logerror("not enough memory to create thread: %s (%s)", name,
442 memset(pThread, 0, sizeof(*pThread));
444 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
445 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
446 pThread->pvUserData = ud;
447 pThread->pfnEntry = entry;
448 pThread->bMainThread = FALSE;
450 /* Create thread event sem, auto reset. */
451 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
453 if (size < loc_MIN_THREAD_STACK)
454 size = loc_MIN_THREAD_STACK;
456 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
457 if (pThread->ulThreadID == -1) {
458 logerror("can not create thread: %s (%s): %s", name, desc,
463 loc_debug("new thread id is %ld", pThread->ulThreadID);
468 loc_FreeThreadInfo(pThread);
474 /************************
480 empth_t *pThread = TlsGetValue(dwTLSIndex);
485 /************************
491 empth_t *pThread = TlsGetValue(dwTLSIndex);
493 loc_BlockThisThread();
495 loc_debug("empth_exit");
497 if (pThread->bMainThread) {
498 loc_BlockMainThread();
502 TlsSetValue(dwTLSIndex, NULL);
503 loc_FreeThreadInfo(pThread);
508 /************************
511 * Yield processing to another thread.
516 loc_BlockThisThread();
520 /************************
523 * Kill off the thread.
526 empth_terminate(empth_t *pThread)
528 loc_debug("killing thread %s", pThread->szName);
529 pThread->bKilled = TRUE;
531 SetEvent(pThread->hThreadEvent);
534 /************************
537 * Do a select on the given file.
540 * This would be one of the main functions used within gen\io.c
543 empth_select(int fd, int flags)
545 WSAEVENT hEventObject[2];
546 empth_t *pThread = TlsGetValue(dwTLSIndex);
548 loc_debug("%s select on %d",
549 flags == EMPTH_FD_READ ? "read" : "write", fd);
550 loc_BlockThisThread();
552 hEventObject[0] = WSACreateEvent();
553 hEventObject[1] = pThread->hThreadEvent;
555 if (flags == EMPTH_FD_READ)
556 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
557 else if (flags == EMPTH_FD_WRITE)
558 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
560 logerror("bad flag %d passed to empth_select", flags);
564 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
566 WSAEventSelect(fd, hEventObject[0], 0);
568 WSACloseEvent(hEventObject[0]);
573 /************************
576 * Wake up the specified thread.
579 empth_wakeup(empth_t *pThread)
581 loc_debug("waking up thread %s", pThread->szName);
583 /* Let it run if it is blocked... */
584 SetEvent(pThread->hThreadEvent);
587 /************************
590 * Put the given thread to sleep...
593 empth_sleep(time_t until)
597 loc_BlockThisThread();
599 while ((lSec = until - time(0)) > 0) {
600 loc_debug("going to sleep %ld sec", lSec);
604 loc_debug("sleep done. Waiting to run.");
610 /************************
613 * Create a signalling semaphore.
616 empth_sem_create(char *name, int cnt)
620 pSem = malloc(sizeof(*pSem));
622 logerror("out of memory at %s:%d", __FILE__, __LINE__);
626 memset(pSem, 0, sizeof(pSem));
627 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
629 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
630 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
636 /************************
639 * Hit/signal the specified semaphore.
642 empth_sem_signal(empth_sem_t *pSem)
644 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
646 /* Wait for the Semaphore */
647 WaitForSingleObject(pSem->hMutex, INFINITE);
649 if (pSem->count++ < 0) {
650 SetEvent(pSem->hEvent);
653 ReleaseMutex(pSem->hMutex);
656 /************************
659 * Wait for the specified signal semaphore to be signaled.
662 empth_sem_wait(empth_sem_t *pSem)
664 empth_t *pThread = TlsGetValue(dwTLSIndex);
666 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
668 /* Remove the thread from the running state. */
669 loc_BlockThisThread();
671 /* Wait for the Semaphore */
672 WaitForSingleObject(pSem->hMutex, INFINITE);
673 if (--pSem->count < 0) {
674 loc_debug("blocking");
675 ReleaseMutex(pSem->hMutex);
677 WaitForSingleObject(pSem->hEvent, INFINITE);
679 loc_debug("waking up");
681 ReleaseMutex(pSem->hMutex);