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 /************************
97 * must hold at function call, return, sleep
98 * and resume from sleep.
110 * if read-locked without writers contending:
116 * if read-locked with writers contending:
119 * nwrite > 0 #writers blocked
125 * nwrite > 0 #writers blocked + 1
128 * To ensure consistency, state normally changes only while the
129 * thread changing it holds hThreadMutex.
133 char name[17]; /* The thread name, passed in at create time. */
134 HANDLE can_read; /* Manual event -- allows read locks */
135 HANDLE can_write; /* Auto-reset event -- allows write locks */
136 int nread; /* number of active readers */
137 int nwrite; /* total number of writers (active and waiting) */
140 /* This is the thread exclusion/non-premption mutex. */
141 /* The running thread has this MUTEX, and all others are */
142 /* either blocked on it, or waiting for some OS response. */
143 static HANDLE hThreadMutex;
145 /* This is the thread startup event. */
146 /* We use this to lockstep when we are starting up threads. */
147 static HANDLE hThreadStartEvent;
149 /* This is an event used to wakeup the main thread */
150 /* to start the shutdown sequence. */
151 static HANDLE hShutdownEvent;
153 /* The Thread Local Storage index. We store the pThread pointer */
154 /* for each thread at this index. */
155 static DWORD dwTLSIndex;
157 /* The current running thread. */
158 static empth_t *pCurThread;
161 static unsigned long ulTickAtStart;
163 /* Pointer out to global context. "player". */
164 /* From empth_init parameter. */
165 static void **ppvUserData;
167 /* Global flags. From empth_init parameter. */
168 static int global_flags;
171 /************************
174 * Print out the current thread's status??
177 loc_debug(const char *pszFmt, ...)
180 unsigned long ulCurTick;
181 unsigned long ulRunTick;
182 unsigned long ulMs, ulSec, ulMin, ulHr;
183 empth_t *pThread = TlsGetValue(dwTLSIndex);
186 if ((global_flags & EMPTH_PRINT) != 0) {
188 /* Ticks are in milliseconds */
189 ulCurTick = GetTickCount();
191 ulRunTick = ulCurTick - ulTickAtStart;
192 ulMs = ulRunTick % 1000L;
193 ulSec = (ulRunTick / 1000L) % 60L;
194 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
195 ulHr = (ulRunTick / (60L * 60L * 1000L));
197 va_start(vaList, pszFmt);
198 vsprintf(buf, pszFmt, vaList);
202 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
203 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
205 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
206 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
212 /************************
216 loc_FreeThreadInfo(empth_t *pThread)
219 if (pThread->hThreadEvent)
220 CloseHandle(pThread->hThreadEvent);
221 memset(pThread, 0, sizeof(*pThread));
226 /************************
229 * This thread wants to run.
230 * When this function returns, the globals are set to this thread
231 * info, and the thread owns the MUTEX.
234 loc_RunThisThread(HANDLE hWaitObject)
236 HANDLE hWaitObjects[2];
238 empth_t *pThread = TlsGetValue(dwTLSIndex);
240 if (pThread->bKilled) {
241 if (!pThread->bMainThread) {
242 TlsSetValue(dwTLSIndex, NULL);
243 loc_FreeThreadInfo(pThread);
248 hWaitObjects[0] = hThreadMutex;
249 hWaitObjects[1] = hWaitObject;
251 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
255 /* Set the globals to this thread. */
256 *ppvUserData = pThread->pvUserData;
258 pCurThread = pThread;
260 /* Hmm, a problem, eh? */
261 logerror("RunThisThread, someone already running.");
265 /************************
266 * loc_BlockThisThread
268 * This thread was running. It no longer wants to.
271 loc_BlockThisThread(void)
273 empth_t *pThread = TlsGetValue(dwTLSIndex);
275 if (pCurThread == pThread) {
276 /* Reset the globals back to original */
281 /* Release the MUTEX */
282 ReleaseMutex(hThreadMutex);
284 /* Hmm, this thread was not the running one. */
285 logerror("BlockThisThread, not running.");
289 /************************
292 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
293 * System-Shutdown will initiate a shutdown.
294 * This is done by calling empth_request_shutdown()
297 loc_Exit_Handler(DWORD fdwCtrlType)
299 switch (fdwCtrlType) {
301 case CTRL_CLOSE_EVENT:
302 case CTRL_BREAK_EVENT:
303 case CTRL_LOGOFF_EVENT:
304 case CTRL_SHUTDOWN_EVENT:
305 empth_request_shutdown();
312 /************************
315 * This is the main line of each thread.
316 * This is really a static local func....
319 empth_threadMain(void *pvData)
323 empth_t *pThread = pvData;
329 /* Store pThread on this thread. */
330 TlsSetValue(dwTLSIndex, pvData);
332 /* Get the ID of the thread. */
333 pThread->ulThreadID = GetCurrentThreadId();
335 /* Signal that the thread has started. */
336 SetEvent(hThreadStartEvent);
338 /* seed the rand() function */
340 srand(now ^ (unsigned)pThread);
342 /* Switch to this thread context */
343 loc_RunThisThread(NULL);
345 /* Run the thread. */
346 if (pThread->pfnEntry)
347 pThread->pfnEntry(pThread->pvUserData);
349 /* Kill the thread. */
353 /************************
356 * Initialize the thread environment.
358 * This is called from the program main line.
361 empth_init(void **ctx_ptr, int flags)
363 empth_t *pThread = NULL;
365 ulTickAtStart = GetTickCount();
366 ppvUserData = ctx_ptr;
367 global_flags = flags;
368 dwTLSIndex = TlsAlloc();
370 /* Create the thread mutex. */
371 /* Initally unowned. */
372 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
374 logerror("Failed to create mutex %lu", GetLastError());
378 /* Create the thread start event. */
379 /* Automatic state reset. */
380 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
381 if (!hThreadStartEvent) {
382 logerror("Failed to create start event %lu", GetLastError());
386 /* Create the shutdown event for the main thread. */
388 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
389 if (!hShutdownEvent) {
390 logerror("Failed to create shutdown event %lu", GetLastError());
393 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
395 /* Create the global Thread context. */
396 pThread = malloc(sizeof(*pThread));
398 logerror("not enough memory to create main thread.");
401 memset(pThread, 0, sizeof(*pThread));
403 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
404 pThread->ulThreadID = GetCurrentThreadId();
405 pThread->bMainThread = TRUE;
407 TlsSetValue(dwTLSIndex, pThread);
409 /* Make this the running thread. */
410 loc_RunThisThread(NULL);
412 logerror("NT pthreads initialized");
417 /************************
420 * Create a new thread.
422 * prio - priority, not particularly useful in our context.
423 * entry - entry point function for thread.
425 * flags - debug control.
426 * LWP_STACKCHECK - not needed
427 * name - name of the thread, for debug.
428 * ud - "user data". The "ctx_ptr" gets this value
429 * when the thread is active.
430 * It is also passed to the entry function...
433 empth_create(int prio, void (*entry)(void *), int size, int flags,
434 char *name, void *ud)
436 empth_t *pThread = NULL;
438 loc_debug("creating new thread %s", name);
440 pThread = malloc(sizeof(*pThread));
442 logerror("not enough memory to create thread %s", name);
445 memset(pThread, 0, sizeof(*pThread));
447 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
448 pThread->pvUserData = ud;
449 pThread->pfnEntry = entry;
450 pThread->bMainThread = FALSE;
452 /* Create thread event, auto reset. */
453 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
455 if (size < loc_MIN_THREAD_STACK)
456 size = loc_MIN_THREAD_STACK;
458 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
459 if (pThread->ulThreadID == -1) {
460 logerror("can not create thread: %s: %s", name, strerror(errno));
464 loc_debug("new thread id is %ld", pThread->ulThreadID);
470 loc_FreeThreadInfo(pThread);
476 /************************
482 empth_t *pThread = TlsGetValue(dwTLSIndex);
487 /************************
493 empth_t *pThread = TlsGetValue(dwTLSIndex);
495 loc_debug("empth_exit");
496 loc_BlockThisThread();
498 TlsSetValue(dwTLSIndex, NULL);
499 loc_FreeThreadInfo(pThread);
503 /************************
506 * Yield processing to another thread.
511 loc_BlockThisThread();
512 loc_RunThisThread(NULL);
515 /************************
518 * Kill off the thread.
521 empth_terminate(empth_t *pThread)
523 loc_debug("killing thread %s", pThread->szName);
524 pThread->bKilled = TRUE;
526 SetEvent(pThread->hThreadEvent);
529 /************************
532 * Do a select on the given file.
535 * This would be one of the main functions used within gen\io.c
538 empth_select(int fd, int flags)
540 WSAEVENT hEventObject[2];
541 empth_t *pThread = TlsGetValue(dwTLSIndex);
543 loc_debug("%s select on %d",
544 flags == EMPTH_FD_READ ? "read" : "write", fd);
545 loc_BlockThisThread();
547 hEventObject[0] = WSACreateEvent();
548 hEventObject[1] = pThread->hThreadEvent;
550 if (flags == EMPTH_FD_READ)
551 WSAEventSelect(fd, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
552 else if (flags == EMPTH_FD_WRITE)
553 WSAEventSelect(fd, hEventObject[0], FD_WRITE | FD_CLOSE);
555 logerror("bad flag %d passed to empth_select", flags);
559 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
561 WSAEventSelect(fd, hEventObject[0], 0);
563 WSACloseEvent(hEventObject[0]);
565 loc_RunThisThread(NULL);
568 /************************
571 * Wake up the specified thread.
574 empth_wakeup(empth_t *pThread)
576 loc_debug("waking up thread %s", pThread->szName);
578 /* Let it run if it is blocked... */
579 SetEvent(pThread->hThreadEvent);
582 /************************
585 * Put the given thread to sleep...
588 empth_sleep(time_t until)
591 empth_t *pThread = TlsGetValue(dwTLSIndex);
594 if ((lSec = until - time(0)) > 0) {
595 loc_BlockThisThread();
596 loc_debug("going to sleep %ld sec", lSec);
598 if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
602 loc_debug("sleep done. Waiting to run.");
603 loc_RunThisThread(NULL);
608 /************************
609 * empth_request_shutdown
611 * This wakes up empth_wait_for_signal() so shutdown can proceed.
612 * This is done by signalling hShutdownEvent.
615 empth_request_shutdown(void)
617 SetEvent(hShutdownEvent);
621 empth_wait_for_signal(void)
623 loc_BlockThisThread();
624 loc_RunThisThread(hShutdownEvent);
629 empth_rwlock_create(char *name)
631 empth_rwlock_t *rwlock;
633 rwlock = malloc(sizeof(*rwlock));
637 memset(rwlock, 0, sizeof(*rwlock));
638 strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
640 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
641 logerror("rwlock_create: failed to create reader event %s at %s:%d",
642 name, __FILE__, __LINE__);
647 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
648 logerror("rwlock_create: failed to create writer event %s at %s:%d",
649 name, __FILE__, __LINE__);
650 CloseHandle(rwlock->can_read);
658 empth_rwlock_destroy(empth_rwlock_t *rwlock)
660 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
662 CloseHandle(rwlock->can_read);
663 CloseHandle(rwlock->can_write);
668 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
670 /* block any new readers */
671 ResetEvent(rwlock->can_read);
673 loc_BlockThisThread();
674 loc_RunThisThread(rwlock->can_write);
675 CANT_HAPPEN(rwlock->nread != 0);
679 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
681 loc_BlockThisThread();
682 loc_RunThisThread(rwlock->can_read);
683 ResetEvent(rwlock->can_write);
688 empth_rwlock_unlock(empth_rwlock_t *rwlock)
690 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
692 if (rwlock->nread) { /* holding read lock */
694 if (rwlock->nread == 0)
695 SetEvent(rwlock->can_write);
698 SetEvent(rwlock->can_write);
700 if (rwlock->nwrite == 0)
701 SetEvent(rwlock->can_read);