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>
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. */
73 /* True if this is the main line, and not a real thread. */
76 /* The user data passed in at create time. */
79 /* True if this thread has been killed. */
82 /* The entry function for the thread. */
83 void (*pfnEntry) (void *);
85 /* The system thread ID. */
86 unsigned long ulThreadID;
88 /* An Mutex that the thread will wait/sleep on. */
93 /************************
98 /* The semaphore name, passed in at create time. */
101 /* An Event that the thread(s) will sleep on. */
104 /* The count variable */
108 /************************
112 * must hold at function call, return, sleep
113 * and resume from sleep.
125 * if read-locked without writers contending:
131 * if read-locked with writers contending:
134 * nwrite > 0 #writers blocked
140 * nwrite > 0 #writers blocked + 1
143 * To ensure consistency, state normally changes only while the
144 * thread changing it holds hThreadMutex.
148 char name[17]; /* The thread name, passed in at create time. */
149 HANDLE can_read; /* Manual event -- allows read locks */
150 HANDLE can_write; /* Auto-reset event -- allows write locks */
151 int nread; /* number of active readers */
152 int nwrite; /* total number of writers (active and waiting) */
155 /* This is the thread exclusion/non-premption mutex. */
156 /* The running thread has this MUTEX, and all others are */
157 /* either blocked on it, or waiting for some OS response. */
158 static HANDLE hThreadMutex;
160 /* This is the thread startup event. */
161 /* We use this to lockstep when we are starting up threads. */
162 static HANDLE hThreadStartEvent;
164 /* This is an event used to wakeup the main thread */
165 /* to start the shutdown sequence. */
166 static HANDLE hShutdownEvent;
168 /* The Thread Local Storage index. We store the pThread pointer */
169 /* for each thread at this index. */
170 static DWORD dwTLSIndex;
172 /* The current running thread. */
173 static empth_t *pCurThread;
176 static unsigned long ulTickAtStart;
178 /* Pointer out to global context. "player". */
179 /* From empth_init parameter. */
180 static void **ppvUserData;
182 /* Global flags. From empth_init parameter. */
183 static int global_flags;
186 /************************
189 * Print out the current thread's status??
192 loc_debug(const char *pszFmt, ...)
195 unsigned long ulCurTick;
196 unsigned long ulRunTick;
197 unsigned long ulMs, ulSec, ulMin, ulHr;
198 empth_t *pThread = TlsGetValue(dwTLSIndex);
201 if ((global_flags & EMPTH_PRINT) != 0) {
203 /* Ticks are in milliseconds */
204 ulCurTick = GetTickCount();
206 ulRunTick = ulCurTick - ulTickAtStart;
207 ulMs = ulRunTick % 1000L;
208 ulSec = (ulRunTick / 1000L) % 60L;
209 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
210 ulHr = (ulRunTick / (60L * 60L * 1000L));
212 va_start(vaList, pszFmt);
213 vsprintf(buf, pszFmt, vaList);
217 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
218 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
220 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
221 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
227 /************************
231 loc_FreeThreadInfo(empth_t *pThread)
234 if (pThread->hThreadEvent)
235 CloseHandle(pThread->hThreadEvent);
236 memset(pThread, 0, sizeof(*pThread));
241 /************************
244 * This thread wants to run.
245 * When this function returns, the globals are set to this thread
246 * info, and the thread owns the MUTEX.
249 loc_RunThisThread(HANDLE hWaitObject)
251 HANDLE hWaitObjects[2];
253 empth_t *pThread = TlsGetValue(dwTLSIndex);
255 if (pThread->bKilled) {
256 if (!pThread->bMainThread) {
257 TlsSetValue(dwTLSIndex, NULL);
258 loc_FreeThreadInfo(pThread);
263 hWaitObjects[0] = hThreadMutex;
264 hWaitObjects[1] = hWaitObject;
266 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
270 /* Set the globals to this thread. */
271 *ppvUserData = pThread->pvUserData;
273 pCurThread = pThread;
275 /* Hmm, a problem, eh? */
276 logerror("RunThisThread, someone already running.");
280 /************************
281 * loc_BlockThisThread
283 * This thread was running. It no longer wants to.
286 loc_BlockThisThread(void)
288 empth_t *pThread = TlsGetValue(dwTLSIndex);
290 if (pCurThread == pThread) {
291 /* Reset the globals back to original */
296 /* Release the MUTEX */
297 ReleaseMutex(hThreadMutex);
299 /* Hmm, this thread was not the running one. */
300 logerror("BlockThisThread, not running.");
304 /************************
307 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
308 * System-Shutdown will initiate a shutdown.
309 * This is done by calling empth_request_shutdown()
312 loc_Exit_Handler(DWORD fdwCtrlType)
314 switch (fdwCtrlType) {
316 case CTRL_CLOSE_EVENT:
317 case CTRL_BREAK_EVENT:
318 case CTRL_LOGOFF_EVENT:
319 case CTRL_SHUTDOWN_EVENT:
320 empth_request_shutdown();
327 /************************
330 * This is the main line of each thread.
331 * This is really a static local func....
334 empth_threadMain(void *pvData)
338 empth_t *pThread = pvData;
344 /* Store pThread on this thread. */
345 TlsSetValue(dwTLSIndex, pvData);
347 /* Get the ID of the thread. */
348 pThread->ulThreadID = GetCurrentThreadId();
350 /* Signal that the thread has started. */
351 SetEvent(hThreadStartEvent);
353 /* seed the rand() function */
355 srand(now ^ (unsigned)pThread);
357 /* Switch to this thread context */
358 loc_RunThisThread(NULL);
360 /* Run the thread. */
361 if (pThread->pfnEntry)
362 pThread->pfnEntry(pThread->pvUserData);
364 /* Kill the thread. */
368 /************************
371 * Initialize the thread environment.
373 * This is called from the program main line.
376 empth_init(void **ctx_ptr, int flags)
378 empth_t *pThread = NULL;
380 ulTickAtStart = GetTickCount();
381 ppvUserData = ctx_ptr;
382 global_flags = flags;
383 dwTLSIndex = TlsAlloc();
385 /* Create the thread mutex. */
386 /* Initally unowned. */
387 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
389 logerror("Failed to create mutex %lu", GetLastError());
393 /* Create the thread start event. */
394 /* Automatic state reset. */
395 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
396 if (!hThreadStartEvent) {
397 logerror("Failed to create start event %lu", GetLastError());
401 /* Create the shutdown event for the main thread. */
403 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
404 if (!hShutdownEvent) {
405 logerror("Failed to create shutdown event %lu", GetLastError());
408 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
410 /* Create the global Thread context. */
411 pThread = malloc(sizeof(*pThread));
413 logerror("not enough memory to create main thread.");
416 memset(pThread, 0, sizeof(*pThread));
418 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
419 pThread->ulThreadID = GetCurrentThreadId();
420 pThread->bMainThread = TRUE;
422 TlsSetValue(dwTLSIndex, pThread);
424 /* Make this the running thread. */
425 loc_RunThisThread(NULL);
427 logerror("NT pthreads initialized");
432 /************************
435 * Create a new thread.
437 * prio - priority, not particularly useful in our context.
438 * entry - entry point function for thread.
440 * flags - debug control.
441 * LWP_STACKCHECK - not needed
442 * name - name of the thread, for debug.
443 * ud - "user data". The "ctx_ptr" gets this value
444 * when the thread is active.
445 * It is also passed to the entry function...
448 empth_create(int prio, void (*entry)(void *), int size, int flags,
449 char *name, void *ud)
451 empth_t *pThread = NULL;
453 loc_debug("creating new thread %s", name);
455 pThread = malloc(sizeof(*pThread));
457 logerror("not enough memory to create thread %s", name);
460 memset(pThread, 0, sizeof(*pThread));
462 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
463 pThread->pvUserData = ud;
464 pThread->pfnEntry = entry;
465 pThread->bMainThread = FALSE;
467 /* Create thread event, auto reset. */
468 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
470 if (size < loc_MIN_THREAD_STACK)
471 size = loc_MIN_THREAD_STACK;
473 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
474 if (pThread->ulThreadID == -1) {
475 logerror("can not create thread: %s: %s", name, strerror(errno));
479 loc_debug("new thread id is %ld", pThread->ulThreadID);
485 loc_FreeThreadInfo(pThread);
491 /************************
497 empth_t *pThread = TlsGetValue(dwTLSIndex);
502 /************************
508 empth_t *pThread = TlsGetValue(dwTLSIndex);
510 loc_debug("empth_exit");
511 loc_BlockThisThread();
513 TlsSetValue(dwTLSIndex, NULL);
514 loc_FreeThreadInfo(pThread);
518 /************************
521 * Yield processing to another thread.
526 loc_BlockThisThread();
527 loc_RunThisThread(NULL);
530 /************************
533 * Kill off the thread.
536 empth_terminate(empth_t *pThread)
538 loc_debug("killing thread %s", pThread->szName);
539 pThread->bKilled = TRUE;
541 SetEvent(pThread->hThreadEvent);
544 /************************
547 * Do a select on the given file.
550 * This would be one of the main functions used within gen\io.c
553 empth_select(int fd, int flags)
555 WSAEVENT hEventObject[2];
556 empth_t *pThread = TlsGetValue(dwTLSIndex);
558 loc_debug("%s select on %d",
559 flags == EMPTH_FD_READ ? "read" : "write", fd);
560 loc_BlockThisThread();
562 hEventObject[0] = WSACreateEvent();
563 hEventObject[1] = pThread->hThreadEvent;
565 if (flags == EMPTH_FD_READ)
566 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
567 else if (flags == EMPTH_FD_WRITE)
568 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
570 logerror("bad flag %d passed to empth_select", flags);
574 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
576 WSAEventSelect(fd, hEventObject[0], 0);
578 WSACloseEvent(hEventObject[0]);
580 loc_RunThisThread(NULL);
583 /************************
586 * Wake up the specified thread.
589 empth_wakeup(empth_t *pThread)
591 loc_debug("waking up thread %s", pThread->szName);
593 /* Let it run if it is blocked... */
594 SetEvent(pThread->hThreadEvent);
597 /************************
600 * Put the given thread to sleep...
603 empth_sleep(time_t until)
606 empth_t *pThread = TlsGetValue(dwTLSIndex);
609 if ((lSec = until - time(0)) > 0) {
610 loc_BlockThisThread();
611 loc_debug("going to sleep %ld sec", lSec);
613 if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
617 loc_debug("sleep done. Waiting to run.");
618 loc_RunThisThread(NULL);
623 /************************
624 * empth_request_shutdown
626 * This wakes up empth_wait_for_signal() so shutdown can proceed.
627 * This is done by signalling hShutdownEvent.
630 empth_request_shutdown(void)
632 SetEvent(hShutdownEvent);
636 empth_wait_for_signal(void)
638 loc_BlockThisThread();
639 loc_RunThisThread(hShutdownEvent);
643 /************************
646 * Create a signalling semaphore.
649 empth_sem_create(char *name, int cnt)
653 pSem = malloc(sizeof(*pSem));
655 logerror("out of memory at %s:%d", __FILE__, __LINE__);
659 memset(pSem, 0, sizeof(pSem));
660 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
662 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
668 /************************
671 * Hit/signal the specified semaphore.
674 empth_sem_signal(empth_sem_t *pSem)
676 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
678 if (pSem->count++ < 0) {
679 SetEvent(pSem->hEvent);
683 /************************
686 * Wait for the specified signal semaphore to be signaled.
689 empth_sem_wait(empth_sem_t *pSem)
691 empth_t *pThread = TlsGetValue(dwTLSIndex);
693 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
694 if (--pSem->count < 0) {
695 /* Remove the thread from the running state. */
696 loc_BlockThisThread();
697 loc_debug("blocking");
698 loc_RunThisThread(pSem->hEvent);
699 loc_debug("waking up");
704 empth_rwlock_create(char *name)
706 empth_rwlock_t *rwlock;
708 rwlock = malloc(sizeof(*rwlock));
712 memset(rwlock, 0, sizeof(*rwlock));
713 strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
715 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
716 logerror("rwlock_create: failed to create reader event %s at %s:%d",
717 name, __FILE__, __LINE__);
722 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
723 logerror("rwlock_create: failed to create writer event %s at %s:%d",
724 name, __FILE__, __LINE__);
725 CloseHandle(rwlock->can_read);
733 empth_rwlock_destroy(empth_rwlock_t *rwlock)
735 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
737 CloseHandle(rwlock->can_read);
738 CloseHandle(rwlock->can_write);
743 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
745 /* block any new readers */
746 ResetEvent(rwlock->can_read);
748 loc_BlockThisThread();
749 loc_RunThisThread(rwlock->can_write);
750 CANT_HAPPEN(rwlock->nread != 0);
754 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
756 loc_BlockThisThread();
757 loc_RunThisThread(rwlock->can_read);
758 ResetEvent(rwlock->can_write);
763 empth_rwlock_unlock(empth_rwlock_t *rwlock)
765 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
767 if (rwlock->nread) { /* holding read lock */
769 if (rwlock->nread == 0)
770 SetEvent(rwlock->can_write);
773 SetEvent(rwlock->can_write);
775 if (rwlock->nwrite == 0)
776 SetEvent(rwlock->can_read);