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.
53 #include <sys/types.h>
59 /* Note: unistd.h(posixio.c) is not thread-safe.
60 * It may be used *only* while holding hThreadMutex.
64 #include "empthread.h"
65 #include "prototypes.h"
67 #define loc_MIN_THREAD_STACK 16384
69 /************************
74 /* The thread name, 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 Mutex that the thread will wait/sleep on. */
97 /************************
101 * must hold at function call, return, sleep
102 * and resume from sleep.
114 * if read-locked without writers contending:
120 * if read-locked with writers contending:
123 * nwrite > 0 #writers blocked
129 * nwrite > 0 #writers blocked + 1
132 * To ensure consistency, state normally changes only while the
133 * thread changing it holds hThreadMutex.
137 char name[17]; /* The thread name, passed in at create time. */
138 HANDLE can_read; /* Manual event -- allows read locks */
139 HANDLE can_write; /* Auto-reset event -- allows write locks */
140 int nread; /* number of active readers */
141 int nwrite; /* total number of writers (active and waiting) */
144 /* This is the thread exclusion/non-premption mutex. */
145 /* The running thread has this MUTEX, and all others are */
146 /* either blocked on it, or waiting for some OS response. */
147 static HANDLE hThreadMutex;
149 /* This is the thread startup event. */
150 /* We use this to lockstep when we are starting up threads. */
151 static HANDLE hThreadStartEvent;
153 /* This is an event used to wakeup the main thread */
154 /* to start the shutdown sequence. */
155 static HANDLE hShutdownEvent;
157 /* The Thread Local Storage index. We store the pThread pointer */
158 /* for each thread at this index. */
159 static DWORD dwTLSIndex;
161 /* The current running thread. */
162 static empth_t *pCurThread;
165 static unsigned long ulTickAtStart;
167 /* Pointer out to global context. "player". */
168 /* From empth_init parameter. */
169 static void **ppvUserData;
171 /* Global flags. From empth_init parameter. */
172 static int global_flags;
175 /************************
178 * Print out the current thread's status??
181 loc_debug(const char *pszFmt, ...)
184 unsigned long ulCurTick;
185 unsigned long ulRunTick;
186 unsigned long ulMs, ulSec, ulMin, ulHr;
187 empth_t *pThread = TlsGetValue(dwTLSIndex);
190 if ((global_flags & EMPTH_PRINT) != 0) {
192 /* Ticks are in milliseconds */
193 ulCurTick = GetTickCount();
195 ulRunTick = ulCurTick - ulTickAtStart;
196 ulMs = ulRunTick % 1000L;
197 ulSec = (ulRunTick / 1000L) % 60L;
198 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
199 ulHr = (ulRunTick / (60L * 60L * 1000L));
201 va_start(vaList, pszFmt);
202 vsprintf(buf, pszFmt, vaList);
206 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
207 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
209 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
210 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
216 /************************
220 loc_FreeThreadInfo(empth_t *pThread)
223 if (pThread->hThreadEvent)
224 CloseHandle(pThread->hThreadEvent);
225 memset(pThread, 0, sizeof(*pThread));
230 /************************
233 * This thread wants to run.
234 * When this function returns, the globals are set to this thread
235 * info, and the thread owns the MUTEX.
238 loc_RunThisThread(HANDLE hWaitObject)
240 HANDLE hWaitObjects[2];
242 empth_t *pThread = TlsGetValue(dwTLSIndex);
244 if (pThread->bKilled) {
245 if (!pThread->bMainThread) {
246 TlsSetValue(dwTLSIndex, NULL);
247 loc_FreeThreadInfo(pThread);
252 hWaitObjects[0] = hThreadMutex;
253 hWaitObjects[1] = hWaitObject;
255 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
259 /* Set the globals to this thread. */
260 *ppvUserData = pThread->pvUserData;
262 pCurThread = pThread;
264 /* Hmm, a problem, eh? */
265 logerror("RunThisThread, someone already running.");
269 /************************
270 * loc_BlockThisThread
272 * This thread was running. It no longer wants to.
275 loc_BlockThisThread(void)
277 empth_t *pThread = TlsGetValue(dwTLSIndex);
279 if (pCurThread == pThread) {
280 /* Reset the globals back to original */
285 /* Release the MUTEX */
286 ReleaseMutex(hThreadMutex);
288 /* Hmm, this thread was not the running one. */
289 logerror("BlockThisThread, not running.");
293 /************************
296 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
297 * System-Shutdown will initiate a shutdown.
298 * This is done by calling empth_request_shutdown()
301 loc_Exit_Handler(DWORD fdwCtrlType)
303 switch (fdwCtrlType) {
305 case CTRL_CLOSE_EVENT:
306 case CTRL_BREAK_EVENT:
307 case CTRL_LOGOFF_EVENT:
308 case CTRL_SHUTDOWN_EVENT:
309 empth_request_shutdown();
316 /************************
319 * This is the main line of each thread.
320 * This is really a static local func....
321 * Note: As the POSIX compatibility layer is not thread safe
322 * this function can not open or create any files or sockets until
323 * loc_RunThisThread() is called
326 empth_threadMain(void *pvData)
330 empth_t *pThread = pvData;
336 /* Store pThread on this thread. */
337 TlsSetValue(dwTLSIndex, pvData);
339 /* Get the ID of the thread. */
340 pThread->ulThreadID = GetCurrentThreadId();
342 /* Signal that the thread has started. */
343 SetEvent(hThreadStartEvent);
345 /* seed the rand() function */
347 srand(now ^ (unsigned)pThread);
349 /* Switch to this thread context */
350 loc_RunThisThread(NULL);
352 /* Run the thread. */
353 if (pThread->pfnEntry)
354 pThread->pfnEntry(pThread->pvUserData);
356 /* Kill the thread. */
360 /************************
363 * Initialize the thread environment.
365 * This is called from the program main line.
368 empth_init(void **ctx_ptr, int flags)
370 empth_t *pThread = NULL;
372 ulTickAtStart = GetTickCount();
373 ppvUserData = ctx_ptr;
374 global_flags = flags;
375 dwTLSIndex = TlsAlloc();
377 /* Create the thread mutex. */
378 /* Initally unowned. */
379 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
381 logerror("Failed to create mutex %lu", GetLastError());
385 /* Create the thread start event. */
386 /* Automatic state reset. */
387 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
388 if (!hThreadStartEvent) {
389 logerror("Failed to create start event %lu", GetLastError());
393 /* Create the shutdown event for the main thread. */
395 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
396 if (!hShutdownEvent) {
397 logerror("Failed to create shutdown event %lu", GetLastError());
400 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
402 /* Create the global Thread context. */
403 pThread = malloc(sizeof(*pThread));
405 logerror("not enough memory to create main thread.");
408 memset(pThread, 0, sizeof(*pThread));
410 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
411 pThread->ulThreadID = GetCurrentThreadId();
412 pThread->bMainThread = TRUE;
414 TlsSetValue(dwTLSIndex, pThread);
416 /* Make this the running thread. */
417 loc_RunThisThread(NULL);
419 logerror("NT pthreads initialized");
424 /************************
427 * Create a new thread.
429 * entry - entry point function for thread.
431 * flags - debug control.
432 * LWP_STACKCHECK - not needed
433 * name - name of the thread, for debug.
434 * ud - "user data". The "ctx_ptr" gets this value
435 * when the thread is active.
436 * It is also passed to the entry function...
439 empth_create(void (*entry)(void *), int size, int flags,
440 char *name, void *ud)
442 empth_t *pThread = NULL;
444 loc_debug("creating new thread %s", name);
446 pThread = malloc(sizeof(*pThread));
448 logerror("not enough memory to create thread %s", name);
451 memset(pThread, 0, sizeof(*pThread));
453 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
454 pThread->pvUserData = ud;
455 pThread->pfnEntry = entry;
456 pThread->bMainThread = FALSE;
458 /* Create thread event, auto reset. */
459 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
461 if (size < loc_MIN_THREAD_STACK)
462 size = loc_MIN_THREAD_STACK;
464 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
465 if (pThread->ulThreadID == 1L) {
466 logerror("can not create thread: %s: %s", name, strerror(errno));
470 loc_debug("new thread id is %ld", pThread->ulThreadID);
476 loc_FreeThreadInfo(pThread);
482 /************************
488 empth_t *pThread = TlsGetValue(dwTLSIndex);
493 /************************
499 empth_t *pThread = TlsGetValue(dwTLSIndex);
501 loc_debug("empth_exit");
502 loc_BlockThisThread();
504 TlsSetValue(dwTLSIndex, NULL);
505 loc_FreeThreadInfo(pThread);
509 /************************
512 * Yield processing to another thread.
517 loc_BlockThisThread();
518 loc_RunThisThread(NULL);
521 /************************
524 * Kill off the thread.
527 empth_terminate(empth_t *pThread)
529 loc_debug("killing thread %s", pThread->szName);
530 pThread->bKilled = TRUE;
532 SetEvent(pThread->hThreadEvent);
535 /************************
538 * Do a select on the given file.
541 * This would be one of the main functions used within gen\io.c
544 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 handle = posix_fd2socket(fd);
558 CANT_HAPPEN(handle < 0);
560 if (flags == EMPTH_FD_READ)
561 WSAEventSelect(handle, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
562 else if (flags == EMPTH_FD_WRITE)
563 WSAEventSelect(handle, hEventObject[0], FD_WRITE | FD_CLOSE);
565 logerror("bad flag %d passed to empth_select", flags);
569 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
571 WSAEventSelect(handle, hEventObject[0], 0);
573 WSACloseEvent(hEventObject[0]);
575 loc_RunThisThread(NULL);
578 /************************
581 * Wake up the specified thread.
584 empth_wakeup(empth_t *pThread)
586 loc_debug("waking up thread %s", pThread->szName);
588 /* Let it run if it is blocked... */
589 SetEvent(pThread->hThreadEvent);
592 /************************
595 * Put the given thread to sleep...
598 empth_sleep(time_t until)
601 empth_t *pThread = TlsGetValue(dwTLSIndex);
604 if ((lSec = until - time(0)) > 0) {
605 loc_BlockThisThread();
606 loc_debug("going to sleep %ld sec", lSec);
608 if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
612 loc_debug("sleep done. Waiting to run.");
613 loc_RunThisThread(NULL);
618 /************************
619 * empth_request_shutdown
621 * This wakes up empth_wait_for_signal() so shutdown can proceed.
622 * This is done by signalling hShutdownEvent.
625 empth_request_shutdown(void)
627 SetEvent(hShutdownEvent);
631 empth_wait_for_signal(void)
633 loc_BlockThisThread();
634 loc_RunThisThread(hShutdownEvent);
639 empth_rwlock_create(char *name)
641 empth_rwlock_t *rwlock;
643 rwlock = malloc(sizeof(*rwlock));
647 memset(rwlock, 0, sizeof(*rwlock));
648 strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
650 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
651 logerror("rwlock_create: failed to create reader event %s at %s:%d",
652 name, __FILE__, __LINE__);
657 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
658 logerror("rwlock_create: failed to create writer event %s at %s:%d",
659 name, __FILE__, __LINE__);
660 CloseHandle(rwlock->can_read);
668 empth_rwlock_destroy(empth_rwlock_t *rwlock)
670 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
672 CloseHandle(rwlock->can_read);
673 CloseHandle(rwlock->can_write);
678 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
680 /* block any new readers */
681 ResetEvent(rwlock->can_read);
683 loc_BlockThisThread();
684 loc_RunThisThread(rwlock->can_write);
685 CANT_HAPPEN(rwlock->nread != 0);
689 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
691 loc_BlockThisThread();
692 loc_RunThisThread(rwlock->can_read);
693 ResetEvent(rwlock->can_write);
698 empth_rwlock_unlock(empth_rwlock_t *rwlock)
700 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
702 if (rwlock->nread) { /* holding read lock */
704 if (rwlock->nread == 0)
705 SetEvent(rwlock->can_write);
708 SetEvent(rwlock->can_write);
710 if (rwlock->nwrite == 0)
711 SetEvent(rwlock->can_read);