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>
58 /* Note: unistd.h(posixio.c) is not thread-safe.
59 * It may be used *only* while holding hThreadMutex.
63 #include "empthread.h"
64 #include "prototypes.h"
66 #define loc_MIN_THREAD_STACK 16384
68 /************************
73 /* The thread name, passed in at create time. */
76 /* True if this is the main line, and not a real thread. */
79 /* The user data passed in at create time. */
82 /* True if this thread has been killed. */
85 /* The entry function for the thread. */
86 void (*pfnEntry) (void *);
88 /* The system thread ID. */
89 unsigned long ulThreadID;
91 /* An Mutex that the thread will wait/sleep on. */
96 /************************
100 * must hold at function call, return, sleep
101 * and resume from sleep.
113 * if read-locked without writers contending:
119 * if read-locked with writers contending:
122 * nwrite > 0 #writers blocked
128 * nwrite > 0 #writers blocked + 1
131 * To ensure consistency, state normally changes only while the
132 * thread changing it holds hThreadMutex.
136 char name[17]; /* The thread name, passed in at create time. */
137 HANDLE can_read; /* Manual event -- allows read locks */
138 HANDLE can_write; /* Auto-reset event -- allows write locks */
139 int nread; /* number of active readers */
140 int nwrite; /* total number of writers (active and waiting) */
143 /* This is the thread exclusion/non-premption mutex. */
144 /* The running thread has this MUTEX, and all others are */
145 /* either blocked on it, or waiting for some OS response. */
146 static HANDLE hThreadMutex;
148 /* This is the thread startup event. */
149 /* We use this to lockstep when we are starting up threads. */
150 static HANDLE hThreadStartEvent;
152 /* This is an event used to wakeup the main thread */
153 /* to start the shutdown sequence. */
154 static HANDLE hShutdownEvent;
156 /* The Thread Local Storage index. We store the pThread pointer */
157 /* for each thread at this index. */
158 static DWORD dwTLSIndex;
160 /* The current running thread. */
161 static empth_t *pCurThread;
164 static unsigned long ulTickAtStart;
166 /* Pointer out to global context. "player". */
167 /* From empth_init parameter. */
168 static void **ppvUserData;
170 /* Global flags. From empth_init parameter. */
171 static int global_flags;
174 /************************
177 * Print out the current thread's status??
180 loc_debug(const char *pszFmt, ...)
183 unsigned long ulCurTick;
184 unsigned long ulRunTick;
185 unsigned long ulMs, ulSec, ulMin, ulHr;
186 empth_t *pThread = TlsGetValue(dwTLSIndex);
189 if ((global_flags & EMPTH_PRINT) != 0) {
191 /* Ticks are in milliseconds */
192 ulCurTick = GetTickCount();
194 ulRunTick = ulCurTick - ulTickAtStart;
195 ulMs = ulRunTick % 1000L;
196 ulSec = (ulRunTick / 1000L) % 60L;
197 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
198 ulHr = (ulRunTick / (60L * 60L * 1000L));
200 va_start(vaList, pszFmt);
201 vsprintf(buf, pszFmt, vaList);
205 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
206 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
208 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
209 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
215 /************************
219 loc_FreeThreadInfo(empth_t *pThread)
222 if (pThread->hThreadEvent)
223 CloseHandle(pThread->hThreadEvent);
224 memset(pThread, 0, sizeof(*pThread));
229 /************************
232 * This thread wants to run.
233 * When this function returns, the globals are set to this thread
234 * info, and the thread owns the MUTEX.
237 loc_RunThisThread(HANDLE hWaitObject)
239 HANDLE hWaitObjects[2];
241 empth_t *pThread = TlsGetValue(dwTLSIndex);
243 if (pThread->bKilled) {
244 if (!pThread->bMainThread) {
245 TlsSetValue(dwTLSIndex, NULL);
246 loc_FreeThreadInfo(pThread);
251 hWaitObjects[0] = hThreadMutex;
252 hWaitObjects[1] = hWaitObject;
254 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
258 /* Set the globals to this thread. */
259 *ppvUserData = pThread->pvUserData;
261 pCurThread = pThread;
263 /* Hmm, a problem, eh? */
264 logerror("RunThisThread, someone already running.");
268 /************************
269 * loc_BlockThisThread
271 * This thread was running. It no longer wants to.
274 loc_BlockThisThread(void)
276 empth_t *pThread = TlsGetValue(dwTLSIndex);
278 if (pCurThread == pThread) {
279 /* Reset the globals back to original */
284 /* Release the MUTEX */
285 ReleaseMutex(hThreadMutex);
287 /* Hmm, this thread was not the running one. */
288 logerror("BlockThisThread, not running.");
292 /************************
295 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
296 * System-Shutdown will initiate a shutdown.
297 * This is done by calling empth_request_shutdown()
300 loc_Exit_Handler(DWORD fdwCtrlType)
302 switch (fdwCtrlType) {
304 case CTRL_CLOSE_EVENT:
305 case CTRL_BREAK_EVENT:
306 case CTRL_LOGOFF_EVENT:
307 case CTRL_SHUTDOWN_EVENT:
308 empth_request_shutdown();
315 /************************
318 * This is the main line of each thread.
319 * This is really a static local func....
320 * Note: As the POSIX compatibility layer is not thread safe
321 * this function can not open or create any files or sockets until
322 * loc_RunThisThread() is called
325 empth_threadMain(void *pvData)
329 empth_t *pThread = pvData;
335 /* Store pThread on this thread. */
336 TlsSetValue(dwTLSIndex, pvData);
338 /* Get the ID of the thread. */
339 pThread->ulThreadID = GetCurrentThreadId();
341 /* Signal that the thread has started. */
342 SetEvent(hThreadStartEvent);
344 /* seed the rand() function */
346 srand(now ^ (unsigned)pThread);
348 /* Switch to this thread context */
349 loc_RunThisThread(NULL);
351 /* Run the thread. */
352 if (pThread->pfnEntry)
353 pThread->pfnEntry(pThread->pvUserData);
355 /* Kill the thread. */
359 /************************
362 * Initialize the thread environment.
364 * This is called from the program main line.
367 empth_init(void **ctx_ptr, int flags)
369 empth_t *pThread = NULL;
371 ulTickAtStart = GetTickCount();
372 ppvUserData = ctx_ptr;
373 global_flags = flags;
374 dwTLSIndex = TlsAlloc();
376 /* Create the thread mutex. */
377 /* Initally unowned. */
378 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
380 logerror("Failed to create mutex %lu", GetLastError());
384 /* Create the thread start event. */
385 /* Automatic state reset. */
386 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
387 if (!hThreadStartEvent) {
388 logerror("Failed to create start event %lu", GetLastError());
392 /* Create the shutdown event for the main thread. */
394 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
395 if (!hShutdownEvent) {
396 logerror("Failed to create shutdown event %lu", GetLastError());
399 SetConsoleCtrlHandler((PHANDLER_ROUTINE)loc_Exit_Handler, TRUE);
401 /* Create the global Thread context. */
402 pThread = malloc(sizeof(*pThread));
404 logerror("not enough memory to create main thread.");
407 memset(pThread, 0, sizeof(*pThread));
409 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
410 pThread->ulThreadID = GetCurrentThreadId();
411 pThread->bMainThread = TRUE;
413 TlsSetValue(dwTLSIndex, pThread);
415 /* Make this the running thread. */
416 loc_RunThisThread(NULL);
418 logerror("NT pthreads initialized");
423 /************************
426 * Create a new thread.
428 * entry - entry point function for thread.
430 * flags - debug control.
431 * LWP_STACKCHECK - not needed
432 * name - name of the thread, for debug.
433 * ud - "user data". The "ctx_ptr" gets this value
434 * when the thread is active.
435 * It is also passed to the entry function...
438 empth_create(void (*entry)(void *), int size, int flags,
439 char *name, void *ud)
441 empth_t *pThread = NULL;
443 loc_debug("creating new thread %s", name);
445 pThread = malloc(sizeof(*pThread));
447 logerror("not enough memory to create thread %s", name);
450 memset(pThread, 0, sizeof(*pThread));
452 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
453 pThread->pvUserData = ud;
454 pThread->pfnEntry = entry;
455 pThread->bMainThread = FALSE;
457 /* Create thread event, auto reset. */
458 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
460 if (size < loc_MIN_THREAD_STACK)
461 size = loc_MIN_THREAD_STACK;
463 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
464 if (pThread->ulThreadID == 1L) {
465 logerror("can not create thread: %s: %s", name, strerror(errno));
469 loc_debug("new thread id is %ld", pThread->ulThreadID);
475 loc_FreeThreadInfo(pThread);
481 /************************
487 empth_t *pThread = TlsGetValue(dwTLSIndex);
492 /************************
498 empth_t *pThread = TlsGetValue(dwTLSIndex);
500 loc_debug("empth_exit");
501 loc_BlockThisThread();
503 TlsSetValue(dwTLSIndex, NULL);
504 loc_FreeThreadInfo(pThread);
508 /************************
511 * Yield processing to another thread.
516 loc_BlockThisThread();
517 loc_RunThisThread(NULL);
520 /************************
523 * Kill off the thread.
526 empth_terminate(empth_t *pThread)
528 loc_debug("killing thread %s", pThread->szName);
529 pThread->bKilled = TRUE;
531 SetEvent(pThread->hThreadEvent);
534 /************************
537 * Do a select on the given file.
540 * This would be one of the main functions used within gen\io.c
543 empth_select(int fd, int flags)
546 WSAEVENT hEventObject[2];
547 empth_t *pThread = TlsGetValue(dwTLSIndex);
549 loc_debug("%s select on %d",
550 flags == EMPTH_FD_READ ? "read" : "write", fd);
551 loc_BlockThisThread();
553 hEventObject[0] = WSACreateEvent();
554 hEventObject[1] = pThread->hThreadEvent;
556 handle = posix_fd2socket(fd);
557 CANT_HAPPEN(handle < 0);
559 if (flags == EMPTH_FD_READ)
560 WSAEventSelect(handle, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
561 else if (flags == EMPTH_FD_WRITE)
562 WSAEventSelect(handle, hEventObject[0], FD_WRITE | FD_CLOSE);
564 logerror("bad flag %d passed to empth_select", flags);
568 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
570 WSAEventSelect(handle, hEventObject[0], 0);
572 WSACloseEvent(hEventObject[0]);
574 loc_RunThisThread(NULL);
577 /************************
580 * Wake up the specified thread.
583 empth_wakeup(empth_t *pThread)
585 loc_debug("waking up thread %s", pThread->szName);
587 /* Let it run if it is blocked... */
588 SetEvent(pThread->hThreadEvent);
591 /************************
594 * Put the given thread to sleep...
597 empth_sleep(time_t until)
600 empth_t *pThread = TlsGetValue(dwTLSIndex);
603 if ((lSec = until - time(0)) > 0) {
604 loc_BlockThisThread();
605 loc_debug("going to sleep %ld sec", lSec);
607 if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
611 loc_debug("sleep done. Waiting to run.");
612 loc_RunThisThread(NULL);
617 /************************
618 * empth_request_shutdown
620 * This wakes up empth_wait_for_signal() so shutdown can proceed.
621 * This is done by signalling hShutdownEvent.
624 empth_request_shutdown(void)
626 SetEvent(hShutdownEvent);
630 empth_wait_for_signal(void)
632 loc_BlockThisThread();
633 loc_RunThisThread(hShutdownEvent);
638 empth_rwlock_create(char *name)
640 empth_rwlock_t *rwlock;
642 rwlock = malloc(sizeof(*rwlock));
646 memset(rwlock, 0, sizeof(*rwlock));
647 strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
649 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
650 logerror("rwlock_create: failed to create reader event %s at %s:%d",
651 name, __FILE__, __LINE__);
656 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
657 logerror("rwlock_create: failed to create writer event %s at %s:%d",
658 name, __FILE__, __LINE__);
659 CloseHandle(rwlock->can_read);
667 empth_rwlock_destroy(empth_rwlock_t *rwlock)
669 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
671 CloseHandle(rwlock->can_read);
672 CloseHandle(rwlock->can_write);
677 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
679 /* block any new readers */
680 ResetEvent(rwlock->can_read);
682 loc_BlockThisThread();
683 loc_RunThisThread(rwlock->can_write);
684 CANT_HAPPEN(rwlock->nread != 0);
688 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
690 loc_BlockThisThread();
691 loc_RunThisThread(rwlock->can_read);
692 ResetEvent(rwlock->can_write);
697 empth_rwlock_unlock(empth_rwlock_t *rwlock)
699 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
701 if (rwlock->nread) { /* holding read lock */
703 if (rwlock->nread == 0)
704 SetEvent(rwlock->can_write);
707 SetEvent(rwlock->can_write);
709 if (rwlock->nwrite == 0)
710 SetEvent(rwlock->can_read);