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 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 /************************
115 * must hold at function call, return, sleep
116 * and resume from sleep.
128 * if read-locked without writers contending:
134 * if read-locked with writers contending:
137 * nwrite > 0 #writers blocked
143 * nwrite > 0 #writers blocked + 1
146 * To ensure consistency, state normally changes only while the
147 * thread changing it holds hThreadMutex.
150 struct loc_RWLock_t {
151 char name[17]; /* The thread name, passed in at create time. */
152 HANDLE can_read; /* Manual event -- allows read locks */
153 HANDLE can_write; /* Auto-reset event -- allows write locks */
154 int nread; /* number of active readers */
155 int nwrite; /* total number of writers (active and waiting) */
158 /* This is the thread exclusion/non-premption mutex. */
159 /* The running thread has this MUTEX, and all others are */
160 /* either blocked on it, or waiting for some OS response. */
161 static HANDLE hThreadMutex;
163 /* This is the thread startup event sem. */
164 /* We use this to lockstep when we are starting up threads. */
165 static HANDLE hThreadStartEvent;
167 /* This is an event used to wakeup the main thread */
168 /* to start the shutdown sequence. */
169 static HANDLE hShutdownEvent;
171 /* The Thread Local Storage index. We store the pThread pointer */
172 /* for each thread at this index. */
173 static DWORD dwTLSIndex;
175 /* The current running thread. */
176 static empth_t *pCurThread;
179 static unsigned long ulTickAtStart;
181 /* Pointer out to global context. "player". */
182 /* From empth_init parameter. */
183 static void **ppvUserData;
185 /* Global flags. From empth_init parameter. */
186 static int global_flags;
189 /************************
192 * Print out the current thread's status??
195 loc_debug(const char *pszFmt, ...)
198 unsigned long ulCurTick;
199 unsigned long ulRunTick;
200 unsigned long ulMs, ulSec, ulMin, ulHr;
201 empth_t *pThread = TlsGetValue(dwTLSIndex);
204 if ((global_flags & EMPTH_PRINT) != 0) {
206 /* Ticks are in milliseconds */
207 ulCurTick = GetTickCount();
209 ulRunTick = ulCurTick - ulTickAtStart;
210 ulMs = ulRunTick % 1000L;
211 ulSec = (ulRunTick / 1000L) % 60L;
212 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
213 ulHr = (ulRunTick / (60L * 60L * 1000L));
215 va_start(vaList, pszFmt);
216 vsprintf(buf, pszFmt, vaList);
220 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
221 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
223 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
224 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
230 /************************
234 loc_FreeThreadInfo(empth_t *pThread)
237 if (pThread->hThreadEvent)
238 CloseHandle(pThread->hThreadEvent);
239 memset(pThread, 0, sizeof(*pThread));
244 /************************
247 * This thread wants to run.
248 * When this function returns, the globals are set to this thread
249 * info, and the thread owns the MUTEX sem.
252 loc_RunThisThread(HANDLE hWaitObject)
254 HANDLE hWaitObjects[2];
256 empth_t *pThread = TlsGetValue(dwTLSIndex);
258 if (pThread->bKilled) {
259 if (!pThread->bMainThread) {
260 TlsSetValue(dwTLSIndex, NULL);
261 loc_FreeThreadInfo(pThread);
266 hWaitObjects[0] = hThreadMutex;
267 hWaitObjects[1] = hWaitObject;
269 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
273 /* Set the globals to this thread. */
274 *ppvUserData = pThread->pvUserData;
276 pCurThread = pThread;
278 /* Hmm, a problem, eh? */
279 logerror("RunThisThread, someone already running.");
283 /************************
284 * loc_BlockThisThread
286 * This thread was running. It no longer wants to.
289 loc_BlockThisThread(void)
291 empth_t *pThread = TlsGetValue(dwTLSIndex);
293 if (pCurThread == pThread) {
294 /* Reset the globals back to original */
299 /* Release the MUTEX */
300 ReleaseMutex(hThreadMutex);
302 /* Hmm, this thread was not the running one. */
303 logerror("BlockThisThread, not running.");
307 /************************
310 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
311 * System-Shutdown will initiate a shutdown.
312 * This is done by calling empth_request_shutdown()
315 loc_Exit_Handler(DWORD fdwCtrlType)
317 switch (fdwCtrlType) {
319 case CTRL_CLOSE_EVENT:
320 case CTRL_BREAK_EVENT:
321 case CTRL_LOGOFF_EVENT:
322 case CTRL_SHUTDOWN_EVENT:
323 empth_request_shutdown();
330 /************************
333 * This is the main line of each thread.
334 * This is really a static local func....
337 empth_threadMain(void *pvData)
341 empth_t *pThread = pvData;
347 /* Store pThread on this thread. */
348 TlsSetValue(dwTLSIndex, pvData);
350 /* Get the ID of the thread. */
351 pThread->ulThreadID = GetCurrentThreadId();
353 /* Signal that the thread has started. */
354 SetEvent(hThreadStartEvent);
356 /* seed the rand() function */
358 srand(now ^ (unsigned)pThread);
360 /* Switch to this thread context */
361 loc_RunThisThread(NULL);
363 /* Run the thread. */
364 if (pThread->pfnEntry)
365 pThread->pfnEntry(pThread->pvUserData);
367 /* Kill the thread. */
371 /************************
374 * Initialize the thread environment.
376 * This is called from the program main line.
379 empth_init(void **ctx_ptr, int flags)
381 empth_t *pThread = NULL;
383 ulTickAtStart = GetTickCount();
384 ppvUserData = ctx_ptr;
385 global_flags = flags;
386 dwTLSIndex = TlsAlloc();
388 /* Create the thread mutex sem. */
389 /* Initally unowned. */
390 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
392 logerror("Failed to create mutex %lu", GetLastError());
396 /* Create the thread start event sem. */
397 /* Automatic state reset. */
398 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
399 if (!hThreadStartEvent) {
400 logerror("Failed to create start event %lu", GetLastError());
404 /* Create the shutdown event for the main thread. */
406 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
407 if (!hShutdownEvent) {
408 logerror("Failed to create shutdown event %lu", GetLastError());
411 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
413 /* Create the global Thread context. */
414 pThread = malloc(sizeof(*pThread));
416 logerror("not enough memory to create main thread.");
419 memset(pThread, 0, sizeof(*pThread));
421 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
422 strncpy(pThread->szDesc, "The main process",
423 sizeof(pThread->szDesc) - 1);
424 pThread->ulThreadID = GetCurrentThreadId();
425 pThread->bMainThread = TRUE;
427 TlsSetValue(dwTLSIndex, pThread);
429 /* Make this the running thread. */
430 loc_RunThisThread(NULL);
432 logerror("NT pthreads initialized");
437 /************************
440 * Create a new thread.
442 * prio - priority, not particularly useful in our context.
443 * entry - entry point function for thread.
445 * flags - debug control.
446 * LWP_STACKCHECK - not needed
447 * name - name of the thread, for debug.
448 * desc - description of thread, for debug.
449 * ud - "user data". The "ctx_ptr" gets this value
450 * when the thread is active.
451 * It is also passed to the entry function...
454 empth_create(int prio, void (*entry)(void *), int size, int flags,
455 char *name, char *desc, void *ud)
457 empth_t *pThread = NULL;
459 loc_debug("creating new thread %s:%s", name, desc);
461 pThread = malloc(sizeof(*pThread));
463 logerror("not enough memory to create thread: %s (%s)",
467 memset(pThread, 0, sizeof(*pThread));
469 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
470 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
471 pThread->pvUserData = ud;
472 pThread->pfnEntry = entry;
473 pThread->bMainThread = FALSE;
475 /* Create thread event sem, auto reset. */
476 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
478 if (size < loc_MIN_THREAD_STACK)
479 size = loc_MIN_THREAD_STACK;
481 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
482 if (pThread->ulThreadID == -1) {
483 logerror("can not create thread: %s (%s): %s",
484 name, desc, strerror(errno));
488 loc_debug("new thread id is %ld", pThread->ulThreadID);
494 loc_FreeThreadInfo(pThread);
500 /************************
506 empth_t *pThread = TlsGetValue(dwTLSIndex);
511 /************************
517 empth_t *pThread = TlsGetValue(dwTLSIndex);
519 loc_debug("empth_exit");
520 loc_BlockThisThread();
522 TlsSetValue(dwTLSIndex, NULL);
523 loc_FreeThreadInfo(pThread);
527 /************************
530 * Yield processing to another thread.
535 loc_BlockThisThread();
536 loc_RunThisThread(NULL);
539 /************************
542 * Kill off the thread.
545 empth_terminate(empth_t *pThread)
547 loc_debug("killing thread %s", pThread->szName);
548 pThread->bKilled = TRUE;
550 SetEvent(pThread->hThreadEvent);
553 /************************
556 * Do a select on the given file.
559 * This would be one of the main functions used within gen\io.c
562 empth_select(int fd, int flags)
564 WSAEVENT hEventObject[2];
565 empth_t *pThread = TlsGetValue(dwTLSIndex);
567 loc_debug("%s select on %d",
568 flags == EMPTH_FD_READ ? "read" : "write", fd);
569 loc_BlockThisThread();
571 hEventObject[0] = WSACreateEvent();
572 hEventObject[1] = pThread->hThreadEvent;
574 if (flags == EMPTH_FD_READ)
575 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
576 else if (flags == EMPTH_FD_WRITE)
577 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
579 logerror("bad flag %d passed to empth_select", flags);
583 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
585 WSAEventSelect(fd, hEventObject[0], 0);
587 WSACloseEvent(hEventObject[0]);
589 loc_RunThisThread(NULL);
592 /************************
595 * Wake up the specified thread.
598 empth_wakeup(empth_t *pThread)
600 loc_debug("waking up thread %s", pThread->szName);
602 /* Let it run if it is blocked... */
603 SetEvent(pThread->hThreadEvent);
606 /************************
609 * Put the given thread to sleep...
612 empth_sleep(time_t until)
616 loc_BlockThisThread();
618 while ((lSec = until - time(0)) > 0) {
619 loc_debug("going to sleep %ld sec", lSec);
623 loc_debug("sleep done. Waiting to run.");
625 loc_RunThisThread(NULL);
628 /************************
629 * empth_request_shutdown
631 * This wakes up empth_wait_for_signal() so shutdown can proceed.
632 * This is done by signalling hShutdownEvent.
635 empth_request_shutdown(void)
637 SetEvent(hShutdownEvent);
641 empth_wait_for_signal(void)
643 loc_BlockThisThread();
645 /* Get the MUTEX semaphore, wait the number of MS */
646 WaitForSingleObject(hShutdownEvent, INFINITE);
648 loc_RunThisThread(NULL);
652 /************************
655 * Create a signalling semaphore.
658 empth_sem_create(char *name, int cnt)
662 pSem = malloc(sizeof(*pSem));
664 logerror("out of memory at %s:%d", __FILE__, __LINE__);
668 memset(pSem, 0, sizeof(pSem));
669 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
671 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
672 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
678 /************************
681 * Hit/signal the specified semaphore.
684 empth_sem_signal(empth_sem_t *pSem)
686 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
688 /* Wait for the Semaphore */
689 WaitForSingleObject(pSem->hMutex, INFINITE);
691 if (pSem->count++ < 0) {
692 SetEvent(pSem->hEvent);
695 ReleaseMutex(pSem->hMutex);
698 /************************
701 * Wait for the specified signal semaphore to be signaled.
704 empth_sem_wait(empth_sem_t *pSem)
706 empth_t *pThread = TlsGetValue(dwTLSIndex);
708 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
710 /* Remove the thread from the running state. */
711 loc_BlockThisThread();
713 /* Wait for the Semaphore */
714 WaitForSingleObject(pSem->hMutex, INFINITE);
715 if (--pSem->count < 0) {
716 loc_debug("blocking");
717 ReleaseMutex(pSem->hMutex);
719 WaitForSingleObject(pSem->hEvent, INFINITE);
721 loc_debug("waking up");
723 ReleaseMutex(pSem->hMutex);
725 loc_RunThisThread(NULL);
729 empth_rwlock_create(char *name)
731 empth_rwlock_t *rwlock;
733 rwlock = malloc(sizeof(*rwlock));
737 memset(rwlock, 0, sizeof(*rwlock));
738 strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
740 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
741 logerror("rwlock_create: failed to create reader event %s at %s:%d",
742 name, __FILE__, __LINE__);
747 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
748 logerror("rwlock_create: failed to create writer event %s at %s:%d",
749 name, __FILE__, __LINE__);
750 CloseHandle(rwlock->can_read);
758 empth_rwlock_destroy(empth_rwlock_t *rwlock)
760 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
762 CloseHandle(rwlock->can_read);
763 CloseHandle(rwlock->can_write);
768 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
770 /* block any new readers */
771 ResetEvent(rwlock->can_read);
773 loc_BlockThisThread();
774 loc_RunThisThread(rwlock->can_write);
775 CANT_HAPPEN(rwlock->nread != 0);
779 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
781 loc_BlockThisThread();
782 loc_RunThisThread(rwlock->can_read);
783 ResetEvent(rwlock->can_write);
788 empth_rwlock_unlock(empth_rwlock_t *rwlock)
790 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
792 if (rwlock->nread) { /* holding read lock */
794 if (rwlock->nread == 0)
795 SetEvent(rwlock->can_write);
798 SetEvent(rwlock->can_write);
800 if (rwlock->nwrite == 0)
801 SetEvent(rwlock->can_read);