2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2007, 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-2007
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.
52 #include <sys/types.h>
59 #include "empthread.h"
60 #include "prototypes.h"
62 #define loc_MIN_THREAD_STACK 16384
64 /************************
69 /* The thread name, passed in at create time. */
72 /* True if this is the main line, and not a real thread. */
75 /* The user data passed in at create time. */
78 /* True if this thread has been killed. */
81 /* The entry function for the thread. */
82 void (*pfnEntry) (void *);
84 /* The system thread ID. */
85 unsigned long ulThreadID;
87 /* An Mutex that the thread will wait/sleep on. */
92 /************************
96 * must hold at function call, return, sleep
97 * and resume from sleep.
109 * if read-locked without writers contending:
115 * if read-locked with writers contending:
118 * nwrite > 0 #writers blocked
124 * nwrite > 0 #writers blocked + 1
127 * To ensure consistency, state normally changes only while the
128 * thread changing it holds hThreadMutex.
132 char name[17]; /* The thread name, passed in at create time. */
133 HANDLE can_read; /* Manual event -- allows read locks */
134 HANDLE can_write; /* Auto-reset event -- allows write locks */
135 int nread; /* number of active readers */
136 int nwrite; /* total number of writers (active and waiting) */
139 /* This is the thread exclusion/non-premption mutex. */
140 /* The running thread has this MUTEX, and all others are */
141 /* either blocked on it, or waiting for some OS response. */
142 static HANDLE hThreadMutex;
144 /* This is the thread startup event. */
145 /* We use this to lockstep when we are starting up threads. */
146 static HANDLE hThreadStartEvent;
148 /* This is an event used to wakeup the main thread */
149 /* to start the shutdown sequence. */
150 static HANDLE hShutdownEvent;
152 /* The Thread Local Storage index. We store the pThread pointer */
153 /* for each thread at this index. */
154 static DWORD dwTLSIndex;
156 /* The current running thread. */
157 static empth_t *pCurThread;
160 static unsigned long ulTickAtStart;
162 /* Pointer out to global context. "player". */
163 /* From empth_init parameter. */
164 static void **ppvUserData;
166 /* Global flags. From empth_init parameter. */
167 static int global_flags;
170 /************************
173 * Print out the current thread's status??
176 loc_debug(const char *pszFmt, ...)
179 unsigned long ulCurTick;
180 unsigned long ulRunTick;
181 unsigned long ulMs, ulSec, ulMin, ulHr;
182 empth_t *pThread = TlsGetValue(dwTLSIndex);
185 if ((global_flags & EMPTH_PRINT) != 0) {
187 /* Ticks are in milliseconds */
188 ulCurTick = GetTickCount();
190 ulRunTick = ulCurTick - ulTickAtStart;
191 ulMs = ulRunTick % 1000L;
192 ulSec = (ulRunTick / 1000L) % 60L;
193 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
194 ulHr = (ulRunTick / (60L * 60L * 1000L));
196 va_start(vaList, pszFmt);
197 vsprintf(buf, pszFmt, vaList);
201 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
202 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
204 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
205 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
211 /************************
215 loc_FreeThreadInfo(empth_t *pThread)
218 if (pThread->hThreadEvent)
219 CloseHandle(pThread->hThreadEvent);
220 memset(pThread, 0, sizeof(*pThread));
225 /************************
228 * This thread wants to run.
229 * When this function returns, the globals are set to this thread
230 * info, and the thread owns the MUTEX.
233 loc_RunThisThread(HANDLE hWaitObject)
235 HANDLE hWaitObjects[2];
237 empth_t *pThread = TlsGetValue(dwTLSIndex);
239 if (pThread->bKilled) {
240 if (!pThread->bMainThread) {
241 TlsSetValue(dwTLSIndex, NULL);
242 loc_FreeThreadInfo(pThread);
247 hWaitObjects[0] = hThreadMutex;
248 hWaitObjects[1] = hWaitObject;
250 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
254 /* Set the globals to this thread. */
255 *ppvUserData = pThread->pvUserData;
257 pCurThread = pThread;
259 /* Hmm, a problem, eh? */
260 logerror("RunThisThread, someone already running.");
264 /************************
265 * loc_BlockThisThread
267 * This thread was running. It no longer wants to.
270 loc_BlockThisThread(void)
272 empth_t *pThread = TlsGetValue(dwTLSIndex);
274 if (pCurThread == pThread) {
275 /* Reset the globals back to original */
280 /* Release the MUTEX */
281 ReleaseMutex(hThreadMutex);
283 /* Hmm, this thread was not the running one. */
284 logerror("BlockThisThread, not running.");
288 /************************
291 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
292 * System-Shutdown will initiate a shutdown.
293 * This is done by calling empth_request_shutdown()
296 loc_Exit_Handler(DWORD fdwCtrlType)
298 switch (fdwCtrlType) {
300 case CTRL_CLOSE_EVENT:
301 case CTRL_BREAK_EVENT:
302 case CTRL_LOGOFF_EVENT:
303 case CTRL_SHUTDOWN_EVENT:
304 empth_request_shutdown();
311 /************************
314 * This is the main line of each thread.
315 * This is really a static local func....
318 empth_threadMain(void *pvData)
322 empth_t *pThread = pvData;
328 /* Store pThread on this thread. */
329 TlsSetValue(dwTLSIndex, pvData);
331 /* Get the ID of the thread. */
332 pThread->ulThreadID = GetCurrentThreadId();
334 /* Signal that the thread has started. */
335 SetEvent(hThreadStartEvent);
337 /* seed the rand() function */
339 srand(now ^ (unsigned)pThread);
341 /* Switch to this thread context */
342 loc_RunThisThread(NULL);
344 /* Run the thread. */
345 if (pThread->pfnEntry)
346 pThread->pfnEntry(pThread->pvUserData);
348 /* Kill the thread. */
352 /************************
355 * Initialize the thread environment.
357 * This is called from the program main line.
360 empth_init(void **ctx_ptr, int flags)
362 empth_t *pThread = NULL;
364 ulTickAtStart = GetTickCount();
365 ppvUserData = ctx_ptr;
366 global_flags = flags;
367 dwTLSIndex = TlsAlloc();
369 /* Create the thread mutex. */
370 /* Initally unowned. */
371 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
373 logerror("Failed to create mutex %lu", GetLastError());
377 /* Create the thread start event. */
378 /* Automatic state reset. */
379 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
380 if (!hThreadStartEvent) {
381 logerror("Failed to create start event %lu", GetLastError());
385 /* Create the shutdown event for the main thread. */
387 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
388 if (!hShutdownEvent) {
389 logerror("Failed to create shutdown event %lu", GetLastError());
392 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
394 /* Create the global Thread context. */
395 pThread = malloc(sizeof(*pThread));
397 logerror("not enough memory to create main thread.");
400 memset(pThread, 0, sizeof(*pThread));
402 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
403 pThread->ulThreadID = GetCurrentThreadId();
404 pThread->bMainThread = TRUE;
406 TlsSetValue(dwTLSIndex, pThread);
408 /* Make this the running thread. */
409 loc_RunThisThread(NULL);
411 logerror("NT pthreads initialized");
416 /************************
419 * Create a new thread.
421 * prio - priority, not particularly useful in our context.
422 * entry - entry point function for thread.
424 * flags - debug control.
425 * LWP_STACKCHECK - not needed
426 * name - name of the thread, for debug.
427 * ud - "user data". The "ctx_ptr" gets this value
428 * when the thread is active.
429 * It is also passed to the entry function...
432 empth_create(int prio, void (*entry)(void *), int size, int flags,
433 char *name, void *ud)
435 empth_t *pThread = NULL;
437 loc_debug("creating new thread %s", name);
439 pThread = malloc(sizeof(*pThread));
441 logerror("not enough memory to create thread %s", name);
444 memset(pThread, 0, sizeof(*pThread));
446 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
447 pThread->pvUserData = ud;
448 pThread->pfnEntry = entry;
449 pThread->bMainThread = FALSE;
451 /* Create thread event, 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 == 1L) {
459 logerror("can not create thread: %s: %s", name, strerror(errno));
463 loc_debug("new thread id is %ld", pThread->ulThreadID);
469 loc_FreeThreadInfo(pThread);
475 /************************
481 empth_t *pThread = TlsGetValue(dwTLSIndex);
486 /************************
492 empth_t *pThread = TlsGetValue(dwTLSIndex);
494 loc_debug("empth_exit");
495 loc_BlockThisThread();
497 TlsSetValue(dwTLSIndex, NULL);
498 loc_FreeThreadInfo(pThread);
502 /************************
505 * Yield processing to another thread.
510 loc_BlockThisThread();
511 loc_RunThisThread(NULL);
514 /************************
517 * Kill off the thread.
520 empth_terminate(empth_t *pThread)
522 loc_debug("killing thread %s", pThread->szName);
523 pThread->bKilled = TRUE;
525 SetEvent(pThread->hThreadEvent);
528 /************************
531 * Do a select on the given file.
534 * This would be one of the main functions used within gen\io.c
537 empth_select(int fd, int flags)
539 WSAEVENT hEventObject[2];
540 empth_t *pThread = TlsGetValue(dwTLSIndex);
542 loc_debug("%s select on %d",
543 flags == EMPTH_FD_READ ? "read" : "write", fd);
544 loc_BlockThisThread();
546 hEventObject[0] = WSACreateEvent();
547 hEventObject[1] = pThread->hThreadEvent;
549 if (flags == EMPTH_FD_READ)
550 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
551 else if (flags == EMPTH_FD_WRITE)
552 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
554 logerror("bad flag %d passed to empth_select", flags);
558 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
560 WSAEventSelect(fd, hEventObject[0], 0);
562 WSACloseEvent(hEventObject[0]);
564 loc_RunThisThread(NULL);
567 /************************
570 * Wake up the specified thread.
573 empth_wakeup(empth_t *pThread)
575 loc_debug("waking up thread %s", pThread->szName);
577 /* Let it run if it is blocked... */
578 SetEvent(pThread->hThreadEvent);
581 /************************
584 * Put the given thread to sleep...
587 empth_sleep(time_t until)
590 empth_t *pThread = TlsGetValue(dwTLSIndex);
593 if ((lSec = until - time(0)) > 0) {
594 loc_BlockThisThread();
595 loc_debug("going to sleep %ld sec", lSec);
597 if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
601 loc_debug("sleep done. Waiting to run.");
602 loc_RunThisThread(NULL);
607 /************************
608 * empth_request_shutdown
610 * This wakes up empth_wait_for_signal() so shutdown can proceed.
611 * This is done by signalling hShutdownEvent.
614 empth_request_shutdown(void)
616 SetEvent(hShutdownEvent);
620 empth_wait_for_signal(void)
622 loc_BlockThisThread();
623 loc_RunThisThread(hShutdownEvent);
628 empth_rwlock_create(char *name)
630 empth_rwlock_t *rwlock;
632 rwlock = malloc(sizeof(*rwlock));
636 memset(rwlock, 0, sizeof(*rwlock));
637 strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
639 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
640 logerror("rwlock_create: failed to create reader event %s at %s:%d",
641 name, __FILE__, __LINE__);
646 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
647 logerror("rwlock_create: failed to create writer event %s at %s:%d",
648 name, __FILE__, __LINE__);
649 CloseHandle(rwlock->can_read);
657 empth_rwlock_destroy(empth_rwlock_t *rwlock)
659 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
661 CloseHandle(rwlock->can_read);
662 CloseHandle(rwlock->can_write);
667 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
669 /* block any new readers */
670 ResetEvent(rwlock->can_read);
672 loc_BlockThisThread();
673 loc_RunThisThread(rwlock->can_write);
674 CANT_HAPPEN(rwlock->nread != 0);
678 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
680 loc_BlockThisThread();
681 loc_RunThisThread(rwlock->can_read);
682 ResetEvent(rwlock->can_write);
687 empth_rwlock_unlock(empth_rwlock_t *rwlock)
689 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
691 if (rwlock->nread) { /* holding read lock */
693 if (rwlock->nread == 0)
694 SetEvent(rwlock->can_write);
697 SetEvent(rwlock->can_write);
699 if (rwlock->nwrite == 0)
700 SetEvent(rwlock->can_read);