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)
61 #define loc_MIN_THREAD_STACK 16384
63 /************************
66 * The REAL empth_t thread structure.
67 * The external world only gets a void pointer to this.
69 typedef struct loc_Thread_t {
71 /* The thread name, passed in at create time. */
73 /* The thread description, passed in at create time. */
76 /* True if this is the main line, and not a real thread. */
79 /* The user data passed in at create time. */
82 /* True if this thread has been killed. */
85 /* The entry function for the thread. */
86 void (*pfnEntry) (void *);
88 /* The system thread ID. */
89 unsigned long ulThreadID;
91 /* An Event sem that the thread will wait/sleep on. */
96 /************************
99 * The REAL empth_sem_t structure.
100 * The external world only gets a void pointer to this.
102 typedef struct empth_sem_t {
106 /* An exclusion semaphore for this sem. */
108 /* An Event sem that the thread(s) will sleep on. */
111 /* The count variable */
116 /* This is the thread exclusion/non-premption mutex. */
117 /* The running thread has this MUTEX, and all others are */
118 /* either blocked on it, or waiting for some OS response. */
121 /* This is the thread startup event sem. */
122 /* We use this to lockstep when we are starting up threads. */
123 HANDLE hThreadStartEvent;
125 /* This is an event used to wakeup the main thread */
126 /* to start the shutdown sequence. */
127 HANDLE hShutdownEvent;
129 /* The Thread Local Storage index. We store the pThread pointer */
130 /* for each thread at this index. */
133 /* The current running thread. */
134 loc_Thread_t *pCurThread;
137 unsigned long ulTickAtStart;
139 /* Pointer out to global context. "player". */
140 /* From empth_init parameter. */
143 /* Global flags. From empth_init parameter. */
148 /************************
151 * Print out the current thread's status??
154 loc_debug(const char *pszFmt, ...)
157 unsigned long ulCurTick;
158 unsigned long ulRunTick;
159 unsigned long ulMs, ulSec, ulMin, ulHr;
160 loc_Thread_t *pThread =
161 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
164 if ((loc_GVAR.flags & EMPTH_PRINT) != 0) {
166 /* Ticks are in milliseconds */
167 ulCurTick = GetTickCount();
169 ulRunTick = ulCurTick - loc_GVAR.ulTickAtStart;
170 ulMs = ulRunTick % 1000L;
171 ulSec = (ulRunTick / 1000L) % 60L;
172 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
173 ulHr = (ulRunTick / (60L * 60L * 1000L));
175 va_start(vaList, pszFmt);
176 vsprintf(buf, pszFmt, vaList);
180 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
181 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
183 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
184 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
190 /************************
195 loc_FreeThreadInfo(loc_Thread_t *pThread)
198 if (pThread->hThreadEvent)
199 CloseHandle(pThread->hThreadEvent);
200 memset(pThread, 0, sizeof(*pThread));
205 /************************
208 * This thread wants to run.
209 * When this function returns, the globals are set to this thread
210 * info, and the thread owns the MUTEX sem.
215 loc_Thread_t *pThread =
216 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
218 if (pThread->bKilled) {
219 if (!pThread->bMainThread) {
220 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
221 loc_FreeThreadInfo(pThread);
226 /* Get the MUTEX semaphore, wait forever. */
227 WaitForSingleObject(loc_GVAR.hThreadMutex, INFINITE);
229 if (!loc_GVAR.pCurThread) {
230 /* Set the globals to this thread. */
231 *loc_GVAR.ppvUserData = pThread->pvUserData;
233 loc_GVAR.pCurThread = pThread;
235 /* Hmm, a problem, eh? */
236 logerror("RunThisThread, someone already running.");
240 /************************
241 * loc_BlockThisThread
243 * This thread was running. It no longer wants to.
246 loc_BlockThisThread()
248 loc_Thread_t *pThread =
249 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
251 if (loc_GVAR.pCurThread == pThread) {
252 /* Reset the globals back to original */
254 loc_GVAR.pCurThread = NULL;
255 *loc_GVAR.ppvUserData = NULL;
257 /* Release the MUTEX */
258 ReleaseMutex(loc_GVAR.hThreadMutex);
260 /* Hmm, this thread was not the running one. */
261 logerror("BlockThisThread, not running.");
266 /************************
267 * loc_SleepThisThread
270 loc_SleepThisThread(unsigned long ulMillisecs)
272 loc_Thread_t *pThread =
273 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
275 /* Make sure the event thread is clean. */
276 ResetEvent(pThread->hThreadEvent);
278 /* Get the MUTEX semaphore, wait the number of MS */
279 WaitForSingleObject(pThread->hThreadEvent, ulMillisecs);
283 /************************
286 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
287 * System-Shutdown will initiate a shutdown.
288 * This is done by calling empth_request_shutdown()
291 loc_Exit_Handler(DWORD fdwCtrlType)
296 case CTRL_CLOSE_EVENT:
297 case CTRL_BREAK_EVENT:
298 case CTRL_LOGOFF_EVENT:
299 case CTRL_SHUTDOWN_EVENT:
300 empth_request_shutdown();
307 /************************
308 * empth_request_shutdown
310 * This wakes up the main thread so shutdown can proceed.
311 * This is done by signalling hShutdownEvent.
314 empth_request_shutdown(void)
316 SetEvent(loc_GVAR.hShutdownEvent);
319 /************************
320 * loc_BlockMainThread
322 * This blocks up the main thread. loc_WakeupMainThread() is used
323 * wakeup the main so shutdown can proceed.
326 loc_BlockMainThread(void)
328 /* Get the MUTEX semaphore, wait the number of MS */
329 WaitForSingleObject(loc_GVAR.hShutdownEvent, INFINITE);
332 /************************
335 * This is the main line of each thread.
336 * This is really a static local func....
339 empth_threadMain(void *pvData)
343 loc_Thread_t *pThread = (loc_Thread_t *)pvData;
349 /* Store pThread on this thread. */
350 TlsSetValue(loc_GVAR.dwTLSIndex, pvData);
352 /* Get the ID of the thread. */
353 pThread->ulThreadID = GetCurrentThreadId();
355 /* Signal that the thread has started. */
356 SetEvent(loc_GVAR.hThreadStartEvent);
358 /* seed the rand() function */
360 srand(now ^ (unsigned int)pThread);
362 /* Switch to this thread context */
365 /* Run the thread. */
366 if (pThread->pfnEntry)
367 pThread->pfnEntry(pThread->pvUserData);
369 /* Kill the thread. */
373 /************************
376 * Initialize the thread environment.
378 * This is called from the program main line.
381 empth_init(char **ctx_ptr, int flags)
383 loc_Thread_t *pThread = NULL;
385 loc_GVAR.ulTickAtStart = GetTickCount();
386 loc_GVAR.ppvUserData = ctx_ptr;
387 loc_GVAR.flags = flags;
388 loc_GVAR.dwTLSIndex = TlsAlloc();
390 /* Create the thread mutex sem. */
391 /* Initally unowned. */
392 loc_GVAR.hThreadMutex = CreateMutex(NULL, FALSE, NULL);
393 if (!loc_GVAR.hThreadMutex) {
394 logerror("Failed to create mutex %d", GetLastError());
398 /* Create the thread start event sem. */
399 /* Automatic state reset. */
400 loc_GVAR.hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
401 if (!loc_GVAR.hThreadStartEvent) {
402 logerror("Failed to create start event %d", GetLastError());
406 /* Create the shutdown event for the main thread. */
408 loc_GVAR.hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
409 if (!loc_GVAR.hShutdownEvent) {
410 logerror("Failed to create shutdown event %d", GetLastError());
413 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
415 /* Create the global Thread context. */
416 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
418 logerror("not enough memory to create main thread.");
421 memset(pThread, 0, sizeof(*pThread));
423 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
424 strncpy(pThread->szDesc, "The main process",
425 sizeof(pThread->szDesc) - 1);
426 pThread->ulThreadID = GetCurrentThreadId();
427 pThread->bMainThread = TRUE;
429 TlsSetValue(loc_GVAR.dwTLSIndex, pThread);
431 /* Make this the running thread. */
434 logerror("NT pthreads initialized");
439 /************************
442 * Create a new thread.
444 * prio - priority, not particularly useful in our context.
445 * entry - entry point function for thread.
447 * flags - debug control.
448 * LWP_STACKCHECK - not needed
449 * name - name of the thread, for debug.
450 * desc - description of thread, for debug.
451 * ud - "user data". The "ctx_ptr" gets this value
452 * when the thread is active.
453 * It is also passed to the entry function...
456 empth_create(int prio, void (*entry)(void *), int size, int flags,
457 char *name, char *desc, void *ud)
459 loc_Thread_t *pThread = NULL;
461 loc_debug("creating new thread %s:%s", name, desc);
463 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
465 logerror("not enough memory to create thread: %s (%s)", name,
469 memset(pThread, 0, sizeof(*pThread));
471 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
472 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
473 pThread->pvUserData = ud;
474 pThread->pfnEntry = entry;
475 pThread->bMainThread = FALSE;
477 /* Create thread event sem, auto reset. */
478 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
480 if (size < loc_MIN_THREAD_STACK)
481 size = loc_MIN_THREAD_STACK;
483 pThread->ulThreadID = _beginthread(empth_threadMain, size,
485 if (pThread->ulThreadID == -1) {
486 logerror("can not create thread: %s (%s): %s", name, desc,
491 loc_debug("new thread id is %ld", pThread->ulThreadID);
496 loc_FreeThreadInfo(pThread);
502 /************************
508 loc_Thread_t *pThread =
509 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
514 /************************
520 loc_Thread_t *pThread =
521 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
523 loc_BlockThisThread();
525 loc_debug("empth_exit");
527 if (pThread->bMainThread) {
528 loc_BlockMainThread();
532 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
533 loc_FreeThreadInfo(pThread);
538 /************************
541 * Yield processing to another thread.
546 loc_BlockThisThread();
550 /************************
553 * Kill off the thread.
556 empth_terminate(empth_t *a)
558 loc_Thread_t *pThread = (loc_Thread_t *)a;
560 loc_debug("killing thread %s", pThread->szName);
561 pThread->bKilled = TRUE;
563 SetEvent(pThread->hThreadEvent);
566 /************************
569 * Do a select on the given file.
572 * This would be one of the main functions used within gen\io.c
575 empth_select(int fd, int flags)
577 WSAEVENT hEventObject[2];
578 loc_Thread_t *pThread =
579 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
581 loc_debug("%s select on %d",
582 flags == EMPTH_FD_READ ? "read" : "write", fd);
583 loc_BlockThisThread();
585 hEventObject[0] = WSACreateEvent();
586 hEventObject[1] = pThread->hThreadEvent;
588 if (flags == EMPTH_FD_READ)
589 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
590 else if (flags == EMPTH_FD_WRITE)
591 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
593 logerror("bad flag %d passed to empth_select", flags);
597 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
599 WSAEventSelect(fd, hEventObject[0], 0);
601 WSACloseEvent(hEventObject[0]);
606 /************************
612 loc_Thread_t *pThread =
613 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
615 loc_debug("got alarm signal %d", sig);
617 /* Let it run if it is blocked like... */
618 SetEvent(pThread->hThreadEvent);
621 /************************
624 * Wake up the specified thread.
627 empth_wakeup(empth_t *a)
629 loc_Thread_t *pThread = (loc_Thread_t *)a;
631 loc_debug("waking up thread %s", pThread->szName);
633 /* Let it run if it is blocked... */
634 SetEvent(pThread->hThreadEvent);
637 /************************
640 * Put the given thread to sleep...
643 empth_sleep(long until)
645 loc_Thread_t *pThread =
646 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
649 ulSec = until - time(0);
651 loc_debug("going to sleep %ld sec", ulSec);
653 loc_BlockThisThread();
655 WaitForSingleObject(pThread->hThreadEvent, (ulSec * 1000));
657 loc_debug("sleep done. Waiting to run.");
663 /************************
666 * Create a signalling semaphore.
669 empth_sem_create(char *name, int cnt)
673 pSem = (loc_Sem_t *)malloc(sizeof(*pSem));
675 logerror("out of memory at %s:%d", __FILE__, __LINE__);
679 memset(pSem, 0, sizeof(pSem));
680 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
682 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
683 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
689 /************************
692 * Hit/signal the specified semaphore.
695 empth_sem_signal(empth_sem_t *sm)
697 loc_Sem_t *pSem = (loc_Sem_t *)sm;
699 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
701 /* Wait for the Semaphore */
702 WaitForSingleObject(pSem->hMutex, INFINITE);
704 if (pSem->count++ < 0) {
705 SetEvent(pSem->hEvent);
708 ReleaseMutex(pSem->hMutex);
711 /************************
714 * Wait for the specified signal semaphore to be signaled.
717 empth_sem_wait(empth_sem_t *sm)
719 loc_Thread_t *pThread =
720 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
721 loc_Sem_t *pSem = (loc_Sem_t *)sm;
723 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
725 /* Remove the thread from the running state. */
726 loc_BlockThisThread();
728 /* Wait for the Semaphore */
729 WaitForSingleObject(pSem->hMutex, INFINITE);
730 if (--pSem->count < 0) {
731 loc_debug("blocking");
732 ReleaseMutex(pSem->hMutex);
734 WaitForSingleObject(pSem->hEvent, INFINITE);
736 loc_debug("waking up");
738 ReleaseMutex(pSem->hMutex);