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 empth_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.");
267 /************************
268 * loc_SleepThisThread
271 loc_SleepThisThread(unsigned long ulMillisecs)
273 loc_Thread_t *pThread =
274 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
276 /* Make sure the event thread is clean. */
277 ResetEvent(pThread->hThreadEvent);
279 /* Get the MUTEX semaphore, wait the number of MS */
280 WaitForSingleObject(pThread->hThreadEvent, ulMillisecs);
284 /************************
287 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
288 * System-Shutdown will initiate a shutdown.
289 * This is done by calling empth_request_shutdown()
292 loc_Exit_Handler(DWORD fdwCtrlType)
297 case CTRL_CLOSE_EVENT:
298 case CTRL_BREAK_EVENT:
299 case CTRL_LOGOFF_EVENT:
300 case CTRL_SHUTDOWN_EVENT:
301 empth_request_shutdown();
308 /************************
309 * empth_request_shutdown
311 * This wakes up the main thread so shutdown can proceed.
312 * This is done by signalling hShutdownEvent.
315 empth_request_shutdown(void)
317 SetEvent(loc_GVAR.hShutdownEvent);
320 /************************
321 * loc_BlockMainThread
323 * This blocks up the main thread. loc_WakeupMainThread() is used
324 * wakeup the main so shutdown can proceed.
327 loc_BlockMainThread(void)
329 /* Get the MUTEX semaphore, wait the number of MS */
330 WaitForSingleObject(loc_GVAR.hShutdownEvent, INFINITE);
333 /************************
336 * This is the main line of each thread.
337 * This is really a static local func....
340 empth_threadMain(void *pvData)
344 loc_Thread_t *pThread = (loc_Thread_t *)pvData;
350 /* Store pThread on this thread. */
351 TlsSetValue(loc_GVAR.dwTLSIndex, pvData);
353 /* Get the ID of the thread. */
354 pThread->ulThreadID = GetCurrentThreadId();
356 /* Signal that the thread has started. */
357 SetEvent(loc_GVAR.hThreadStartEvent);
359 /* seed the rand() function */
361 srand(now ^ (unsigned int)pThread);
363 /* Switch to this thread context */
366 /* Run the thread. */
367 if (pThread->pfnEntry)
368 pThread->pfnEntry(pThread->pvUserData);
370 /* Kill the thread. */
374 /************************
377 * Initialize the thread environment.
379 * This is called from the program main line.
382 empth_init(void **ctx_ptr, int flags)
384 loc_Thread_t *pThread = NULL;
386 loc_GVAR.ulTickAtStart = GetTickCount();
387 loc_GVAR.ppvUserData = ctx_ptr;
388 loc_GVAR.flags = flags;
389 loc_GVAR.dwTLSIndex = TlsAlloc();
391 /* Create the thread mutex sem. */
392 /* Initally unowned. */
393 loc_GVAR.hThreadMutex = CreateMutex(NULL, FALSE, NULL);
394 if (!loc_GVAR.hThreadMutex) {
395 logerror("Failed to create mutex %d", GetLastError());
399 /* Create the thread start event sem. */
400 /* Automatic state reset. */
401 loc_GVAR.hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
402 if (!loc_GVAR.hThreadStartEvent) {
403 logerror("Failed to create start event %d", GetLastError());
407 /* Create the shutdown event for the main thread. */
409 loc_GVAR.hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
410 if (!loc_GVAR.hShutdownEvent) {
411 logerror("Failed to create shutdown event %d", GetLastError());
414 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
416 /* Create the global Thread context. */
417 pThread = malloc(sizeof(*pThread));
419 logerror("not enough memory to create main thread.");
422 memset(pThread, 0, sizeof(*pThread));
424 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
425 strncpy(pThread->szDesc, "The main process",
426 sizeof(pThread->szDesc) - 1);
427 pThread->ulThreadID = GetCurrentThreadId();
428 pThread->bMainThread = TRUE;
430 TlsSetValue(loc_GVAR.dwTLSIndex, pThread);
432 /* Make this the running thread. */
435 logerror("NT pthreads initialized");
440 /************************
443 * Create a new thread.
445 * prio - priority, not particularly useful in our context.
446 * entry - entry point function for thread.
448 * flags - debug control.
449 * LWP_STACKCHECK - not needed
450 * name - name of the thread, for debug.
451 * desc - description of thread, for debug.
452 * ud - "user data". The "ctx_ptr" gets this value
453 * when the thread is active.
454 * It is also passed to the entry function...
457 empth_create(int prio, void (*entry)(void *), int size, int flags,
458 char *name, char *desc, void *ud)
460 loc_Thread_t *pThread = NULL;
462 loc_debug("creating new thread %s:%s", name, desc);
464 pThread = malloc(sizeof(*pThread));
466 logerror("not enough memory to create thread: %s (%s)", name,
470 memset(pThread, 0, sizeof(*pThread));
472 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
473 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
474 pThread->pvUserData = ud;
475 pThread->pfnEntry = entry;
476 pThread->bMainThread = FALSE;
478 /* Create thread event sem, auto reset. */
479 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
481 if (size < loc_MIN_THREAD_STACK)
482 size = loc_MIN_THREAD_STACK;
484 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
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(time_t 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 = 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);