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.
51 #include <sys/types.h>
56 #include "empthread.h"
57 #include "prototypes.h"
65 #define loc_MIN_THREAD_STACK 16384
67 /************************
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 /************************
104 /* An exclusion semaphore for this sem. */
106 /* An Event sem that the thread(s) will sleep on. */
109 /* The count variable */
113 /* This is the thread exclusion/non-premption mutex. */
114 /* The running thread has this MUTEX, and all others are */
115 /* either blocked on it, or waiting for some OS response. */
116 static HANDLE hThreadMutex;
118 /* This is the thread startup event sem. */
119 /* We use this to lockstep when we are starting up threads. */
120 static HANDLE hThreadStartEvent;
122 /* This is an event used to wakeup the main thread */
123 /* to start the shutdown sequence. */
124 static HANDLE hShutdownEvent;
126 /* The Thread Local Storage index. We store the pThread pointer */
127 /* for each thread at this index. */
128 static DWORD dwTLSIndex;
130 /* The current running thread. */
131 static empth_t *pCurThread;
134 static unsigned long ulTickAtStart;
136 /* Pointer out to global context. "player". */
137 /* From empth_init parameter. */
138 static void **ppvUserData;
140 /* Global flags. From empth_init parameter. */
141 static int global_flags;
144 /************************
147 * Print out the current thread's status??
150 loc_debug(const char *pszFmt, ...)
153 unsigned long ulCurTick;
154 unsigned long ulRunTick;
155 unsigned long ulMs, ulSec, ulMin, ulHr;
156 empth_t *pThread = TlsGetValue(dwTLSIndex);
159 if ((global_flags & EMPTH_PRINT) != 0) {
161 /* Ticks are in milliseconds */
162 ulCurTick = GetTickCount();
164 ulRunTick = ulCurTick - ulTickAtStart;
165 ulMs = ulRunTick % 1000L;
166 ulSec = (ulRunTick / 1000L) % 60L;
167 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
168 ulHr = (ulRunTick / (60L * 60L * 1000L));
170 va_start(vaList, pszFmt);
171 vsprintf(buf, pszFmt, vaList);
175 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
176 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
178 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
179 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
185 /************************
190 loc_FreeThreadInfo(empth_t *pThread)
193 if (pThread->hThreadEvent)
194 CloseHandle(pThread->hThreadEvent);
195 memset(pThread, 0, sizeof(*pThread));
200 /************************
203 * This thread wants to run.
204 * When this function returns, the globals are set to this thread
205 * info, and the thread owns the MUTEX sem.
208 loc_RunThisThread(void)
210 empth_t *pThread = TlsGetValue(dwTLSIndex);
212 if (pThread->bKilled) {
213 if (!pThread->bMainThread) {
214 TlsSetValue(dwTLSIndex, NULL);
215 loc_FreeThreadInfo(pThread);
220 /* Get the MUTEX semaphore, wait forever. */
221 WaitForSingleObject(hThreadMutex, INFINITE);
224 /* Set the globals to this thread. */
225 *ppvUserData = pThread->pvUserData;
227 pCurThread = pThread;
229 /* Hmm, a problem, eh? */
230 logerror("RunThisThread, someone already running.");
234 /************************
235 * loc_BlockThisThread
237 * This thread was running. It no longer wants to.
240 loc_BlockThisThread(void)
242 empth_t *pThread = TlsGetValue(dwTLSIndex);
244 if (pCurThread == pThread) {
245 /* Reset the globals back to original */
250 /* Release the MUTEX */
251 ReleaseMutex(hThreadMutex);
253 /* Hmm, this thread was not the running one. */
254 logerror("BlockThisThread, not running.");
258 /************************
261 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
262 * System-Shutdown will initiate a shutdown.
263 * This is done by calling empth_request_shutdown()
266 loc_Exit_Handler(DWORD fdwCtrlType)
268 switch (fdwCtrlType) {
270 case CTRL_CLOSE_EVENT:
271 case CTRL_BREAK_EVENT:
272 case CTRL_LOGOFF_EVENT:
273 case CTRL_SHUTDOWN_EVENT:
274 empth_request_shutdown();
281 /************************
282 * empth_request_shutdown
284 * This wakes up the main thread so shutdown can proceed.
285 * This is done by signalling hShutdownEvent.
288 empth_request_shutdown(void)
290 SetEvent(hShutdownEvent);
293 /************************
294 * loc_BlockMainThread
296 * This blocks up the main thread. loc_WakeupMainThread() is used
297 * wakeup the main so shutdown can proceed.
300 loc_BlockMainThread(void)
302 /* Get the MUTEX semaphore, wait the number of MS */
303 WaitForSingleObject(hShutdownEvent, INFINITE);
306 /************************
309 * This is the main line of each thread.
310 * This is really a static local func....
313 empth_threadMain(void *pvData)
317 empth_t *pThread = pvData;
323 /* Store pThread on this thread. */
324 TlsSetValue(dwTLSIndex, pvData);
326 /* Get the ID of the thread. */
327 pThread->ulThreadID = GetCurrentThreadId();
329 /* Signal that the thread has started. */
330 SetEvent(hThreadStartEvent);
332 /* seed the rand() function */
334 srand(now ^ (unsigned)pThread);
336 /* Switch to this thread context */
339 /* Run the thread. */
340 if (pThread->pfnEntry)
341 pThread->pfnEntry(pThread->pvUserData);
343 /* Kill the thread. */
347 /************************
350 * Initialize the thread environment.
352 * This is called from the program main line.
355 empth_init(void **ctx_ptr, int flags)
357 empth_t *pThread = NULL;
359 ulTickAtStart = GetTickCount();
360 ppvUserData = ctx_ptr;
361 global_flags = flags;
362 dwTLSIndex = TlsAlloc();
364 /* Create the thread mutex sem. */
365 /* Initally unowned. */
366 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
368 logerror("Failed to create mutex %lu", GetLastError());
372 /* Create the thread start event sem. */
373 /* Automatic state reset. */
374 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
375 if (!hThreadStartEvent) {
376 logerror("Failed to create start event %lu", GetLastError());
380 /* Create the shutdown event for the main thread. */
382 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
383 if (!hShutdownEvent) {
384 logerror("Failed to create shutdown event %lu", GetLastError());
387 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
389 /* Create the global Thread context. */
390 pThread = malloc(sizeof(*pThread));
392 logerror("not enough memory to create main thread.");
395 memset(pThread, 0, sizeof(*pThread));
397 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
398 strncpy(pThread->szDesc, "The main process",
399 sizeof(pThread->szDesc) - 1);
400 pThread->ulThreadID = GetCurrentThreadId();
401 pThread->bMainThread = TRUE;
403 TlsSetValue(dwTLSIndex, pThread);
405 /* Make this the running thread. */
408 logerror("NT pthreads initialized");
413 /************************
416 * Create a new thread.
418 * prio - priority, not particularly useful in our context.
419 * entry - entry point function for thread.
421 * flags - debug control.
422 * LWP_STACKCHECK - not needed
423 * name - name of the thread, for debug.
424 * desc - description of thread, for debug.
425 * ud - "user data". The "ctx_ptr" gets this value
426 * when the thread is active.
427 * It is also passed to the entry function...
430 empth_create(int prio, void (*entry)(void *), int size, int flags,
431 char *name, char *desc, void *ud)
433 empth_t *pThread = NULL;
435 loc_debug("creating new thread %s:%s", name, desc);
437 pThread = malloc(sizeof(*pThread));
439 logerror("not enough memory to create thread: %s (%s)",
443 memset(pThread, 0, sizeof(*pThread));
445 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
446 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
447 pThread->pvUserData = ud;
448 pThread->pfnEntry = entry;
449 pThread->bMainThread = FALSE;
451 /* Create thread event sem, auto reset. */
452 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
454 if (size < loc_MIN_THREAD_STACK)
455 size = loc_MIN_THREAD_STACK;
457 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
458 if (pThread->ulThreadID == -1) {
459 logerror("can not create thread: %s (%s): %s",
460 name, desc, strerror(errno));
464 loc_debug("new thread id is %ld", pThread->ulThreadID);
470 loc_FreeThreadInfo(pThread);
476 /************************
482 empth_t *pThread = TlsGetValue(dwTLSIndex);
487 /************************
493 empth_t *pThread = TlsGetValue(dwTLSIndex);
495 loc_BlockThisThread();
497 loc_debug("empth_exit");
499 if (pThread->bMainThread) {
500 loc_BlockMainThread();
504 TlsSetValue(dwTLSIndex, NULL);
505 loc_FreeThreadInfo(pThread);
510 /************************
513 * Yield processing to another thread.
518 loc_BlockThisThread();
522 /************************
525 * Kill off the thread.
528 empth_terminate(empth_t *pThread)
530 loc_debug("killing thread %s", pThread->szName);
531 pThread->bKilled = TRUE;
533 SetEvent(pThread->hThreadEvent);
536 /************************
539 * Do a select on the given file.
542 * This would be one of the main functions used within gen\io.c
545 empth_select(int fd, int flags)
547 WSAEVENT hEventObject[2];
548 empth_t *pThread = TlsGetValue(dwTLSIndex);
550 loc_debug("%s select on %d",
551 flags == EMPTH_FD_READ ? "read" : "write", fd);
552 loc_BlockThisThread();
554 hEventObject[0] = WSACreateEvent();
555 hEventObject[1] = pThread->hThreadEvent;
557 if (flags == EMPTH_FD_READ)
558 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
559 else if (flags == EMPTH_FD_WRITE)
560 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
562 logerror("bad flag %d passed to empth_select", flags);
566 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
568 WSAEventSelect(fd, hEventObject[0], 0);
570 WSACloseEvent(hEventObject[0]);
575 /************************
578 * Wake up the specified thread.
581 empth_wakeup(empth_t *pThread)
583 loc_debug("waking up thread %s", pThread->szName);
585 /* Let it run if it is blocked... */
586 SetEvent(pThread->hThreadEvent);
589 /************************
592 * Put the given thread to sleep...
595 empth_sleep(time_t until)
599 loc_BlockThisThread();
601 while ((lSec = until - time(0)) > 0) {
602 loc_debug("going to sleep %ld sec", lSec);
606 loc_debug("sleep done. Waiting to run.");
612 /************************
615 * Create a signalling semaphore.
618 empth_sem_create(char *name, int cnt)
622 pSem = malloc(sizeof(*pSem));
624 logerror("out of memory at %s:%d", __FILE__, __LINE__);
628 memset(pSem, 0, sizeof(pSem));
629 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
631 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
632 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
638 /************************
641 * Hit/signal the specified semaphore.
644 empth_sem_signal(empth_sem_t *pSem)
646 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
648 /* Wait for the Semaphore */
649 WaitForSingleObject(pSem->hMutex, INFINITE);
651 if (pSem->count++ < 0) {
652 SetEvent(pSem->hEvent);
655 ReleaseMutex(pSem->hMutex);
658 /************************
661 * Wait for the specified signal semaphore to be signaled.
664 empth_sem_wait(empth_sem_t *pSem)
666 empth_t *pThread = TlsGetValue(dwTLSIndex);
668 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
670 /* Remove the thread from the running state. */
671 loc_BlockThisThread();
673 /* Wait for the Semaphore */
674 WaitForSingleObject(pSem->hMutex, INFINITE);
675 if (--pSem->count < 0) {
676 loc_debug("blocking");
677 ReleaseMutex(pSem->hMutex);
679 WaitForSingleObject(pSem->hEvent, INFINITE);
681 loc_debug("waking up");
683 ReleaseMutex(pSem->hMutex);