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"
61 #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 /************************
187 loc_FreeThreadInfo(empth_t *pThread)
190 if (pThread->hThreadEvent)
191 CloseHandle(pThread->hThreadEvent);
192 memset(pThread, 0, sizeof(*pThread));
197 /************************
200 * This thread wants to run.
201 * When this function returns, the globals are set to this thread
202 * info, and the thread owns the MUTEX sem.
205 loc_RunThisThread(void)
207 empth_t *pThread = TlsGetValue(dwTLSIndex);
209 if (pThread->bKilled) {
210 if (!pThread->bMainThread) {
211 TlsSetValue(dwTLSIndex, NULL);
212 loc_FreeThreadInfo(pThread);
217 /* Get the MUTEX semaphore, wait forever. */
218 WaitForSingleObject(hThreadMutex, INFINITE);
221 /* Set the globals to this thread. */
222 *ppvUserData = pThread->pvUserData;
224 pCurThread = pThread;
226 /* Hmm, a problem, eh? */
227 logerror("RunThisThread, someone already running.");
231 /************************
232 * loc_BlockThisThread
234 * This thread was running. It no longer wants to.
237 loc_BlockThisThread(void)
239 empth_t *pThread = TlsGetValue(dwTLSIndex);
241 if (pCurThread == pThread) {
242 /* Reset the globals back to original */
247 /* Release the MUTEX */
248 ReleaseMutex(hThreadMutex);
250 /* Hmm, this thread was not the running one. */
251 logerror("BlockThisThread, not running.");
255 /************************
258 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
259 * System-Shutdown will initiate a shutdown.
260 * This is done by calling empth_request_shutdown()
263 loc_Exit_Handler(DWORD fdwCtrlType)
265 switch (fdwCtrlType) {
267 case CTRL_CLOSE_EVENT:
268 case CTRL_BREAK_EVENT:
269 case CTRL_LOGOFF_EVENT:
270 case CTRL_SHUTDOWN_EVENT:
271 empth_request_shutdown();
278 /************************
281 * This is the main line of each thread.
282 * This is really a static local func....
285 empth_threadMain(void *pvData)
289 empth_t *pThread = pvData;
295 /* Store pThread on this thread. */
296 TlsSetValue(dwTLSIndex, pvData);
298 /* Get the ID of the thread. */
299 pThread->ulThreadID = GetCurrentThreadId();
301 /* Signal that the thread has started. */
302 SetEvent(hThreadStartEvent);
304 /* seed the rand() function */
306 srand(now ^ (unsigned)pThread);
308 /* Switch to this thread context */
311 /* Run the thread. */
312 if (pThread->pfnEntry)
313 pThread->pfnEntry(pThread->pvUserData);
315 /* Kill the thread. */
319 /************************
322 * Initialize the thread environment.
324 * This is called from the program main line.
327 empth_init(void **ctx_ptr, int flags)
329 empth_t *pThread = NULL;
331 ulTickAtStart = GetTickCount();
332 ppvUserData = ctx_ptr;
333 global_flags = flags;
334 dwTLSIndex = TlsAlloc();
336 /* Create the thread mutex sem. */
337 /* Initally unowned. */
338 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
340 logerror("Failed to create mutex %lu", GetLastError());
344 /* Create the thread start event sem. */
345 /* Automatic state reset. */
346 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
347 if (!hThreadStartEvent) {
348 logerror("Failed to create start event %lu", GetLastError());
352 /* Create the shutdown event for the main thread. */
354 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
355 if (!hShutdownEvent) {
356 logerror("Failed to create shutdown event %lu", GetLastError());
359 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
361 /* Create the global Thread context. */
362 pThread = malloc(sizeof(*pThread));
364 logerror("not enough memory to create main thread.");
367 memset(pThread, 0, sizeof(*pThread));
369 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
370 strncpy(pThread->szDesc, "The main process",
371 sizeof(pThread->szDesc) - 1);
372 pThread->ulThreadID = GetCurrentThreadId();
373 pThread->bMainThread = TRUE;
375 TlsSetValue(dwTLSIndex, pThread);
377 /* Make this the running thread. */
380 logerror("NT pthreads initialized");
385 /************************
388 * Create a new thread.
390 * prio - priority, not particularly useful in our context.
391 * entry - entry point function for thread.
393 * flags - debug control.
394 * LWP_STACKCHECK - not needed
395 * name - name of the thread, for debug.
396 * desc - description of thread, for debug.
397 * ud - "user data". The "ctx_ptr" gets this value
398 * when the thread is active.
399 * It is also passed to the entry function...
402 empth_create(int prio, void (*entry)(void *), int size, int flags,
403 char *name, char *desc, void *ud)
405 empth_t *pThread = NULL;
407 loc_debug("creating new thread %s:%s", name, desc);
409 pThread = malloc(sizeof(*pThread));
411 logerror("not enough memory to create thread: %s (%s)",
415 memset(pThread, 0, sizeof(*pThread));
417 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
418 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
419 pThread->pvUserData = ud;
420 pThread->pfnEntry = entry;
421 pThread->bMainThread = FALSE;
423 /* Create thread event sem, auto reset. */
424 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
426 if (size < loc_MIN_THREAD_STACK)
427 size = loc_MIN_THREAD_STACK;
429 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
430 if (pThread->ulThreadID == -1) {
431 logerror("can not create thread: %s (%s): %s",
432 name, desc, strerror(errno));
436 loc_debug("new thread id is %ld", pThread->ulThreadID);
442 loc_FreeThreadInfo(pThread);
448 /************************
454 empth_t *pThread = TlsGetValue(dwTLSIndex);
459 /************************
465 empth_t *pThread = TlsGetValue(dwTLSIndex);
467 loc_debug("empth_exit");
468 loc_BlockThisThread();
470 TlsSetValue(dwTLSIndex, NULL);
471 loc_FreeThreadInfo(pThread);
475 /************************
478 * Yield processing to another thread.
483 loc_BlockThisThread();
487 /************************
490 * Kill off the thread.
493 empth_terminate(empth_t *pThread)
495 loc_debug("killing thread %s", pThread->szName);
496 pThread->bKilled = TRUE;
498 SetEvent(pThread->hThreadEvent);
501 /************************
504 * Do a select on the given file.
507 * This would be one of the main functions used within gen\io.c
510 empth_select(int fd, int flags)
512 WSAEVENT hEventObject[2];
513 empth_t *pThread = TlsGetValue(dwTLSIndex);
515 loc_debug("%s select on %d",
516 flags == EMPTH_FD_READ ? "read" : "write", fd);
517 loc_BlockThisThread();
519 hEventObject[0] = WSACreateEvent();
520 hEventObject[1] = pThread->hThreadEvent;
522 if (flags == EMPTH_FD_READ)
523 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
524 else if (flags == EMPTH_FD_WRITE)
525 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
527 logerror("bad flag %d passed to empth_select", flags);
531 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
533 WSAEventSelect(fd, hEventObject[0], 0);
535 WSACloseEvent(hEventObject[0]);
540 /************************
543 * Wake up the specified thread.
546 empth_wakeup(empth_t *pThread)
548 loc_debug("waking up thread %s", pThread->szName);
550 /* Let it run if it is blocked... */
551 SetEvent(pThread->hThreadEvent);
554 /************************
557 * Put the given thread to sleep...
560 empth_sleep(time_t until)
564 loc_BlockThisThread();
566 while ((lSec = until - time(0)) > 0) {
567 loc_debug("going to sleep %ld sec", lSec);
571 loc_debug("sleep done. Waiting to run.");
576 /************************
577 * empth_request_shutdown
579 * This wakes up empth_wait_for_signal() so shutdown can proceed.
580 * This is done by signalling hShutdownEvent.
583 empth_request_shutdown(void)
585 SetEvent(hShutdownEvent);
589 empth_wait_for_signal(void)
591 loc_BlockThisThread();
593 /* Get the MUTEX semaphore, wait the number of MS */
594 WaitForSingleObject(hShutdownEvent, INFINITE);
600 /************************
603 * Create a signalling semaphore.
606 empth_sem_create(char *name, int cnt)
610 pSem = malloc(sizeof(*pSem));
612 logerror("out of memory at %s:%d", __FILE__, __LINE__);
616 memset(pSem, 0, sizeof(pSem));
617 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
619 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
620 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
626 /************************
629 * Hit/signal the specified semaphore.
632 empth_sem_signal(empth_sem_t *pSem)
634 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
636 /* Wait for the Semaphore */
637 WaitForSingleObject(pSem->hMutex, INFINITE);
639 if (pSem->count++ < 0) {
640 SetEvent(pSem->hEvent);
643 ReleaseMutex(pSem->hMutex);
646 /************************
649 * Wait for the specified signal semaphore to be signaled.
652 empth_sem_wait(empth_sem_t *pSem)
654 empth_t *pThread = TlsGetValue(dwTLSIndex);
656 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
658 /* Remove the thread from the running state. */
659 loc_BlockThisThread();
661 /* Wait for the Semaphore */
662 WaitForSingleObject(pSem->hMutex, INFINITE);
663 if (--pSem->count < 0) {
664 loc_debug("blocking");
665 ReleaseMutex(pSem->hMutex);
667 WaitForSingleObject(pSem->hEvent, INFINITE);
669 loc_debug("waking up");
671 ReleaseMutex(pSem->hMutex);