2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2009, 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-2009
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"
68 #define loc_MIN_THREAD_STACK 16384
70 /************************
75 /* The thread name, passed in at create time. */
78 /* True if this is the main line, and not a real thread. */
81 /* The user data passed in at create time. */
84 /* The entry function for the thread. */
85 void (*pfnEntry) (void *);
87 /* The system thread ID. */
88 unsigned long ulThreadID;
90 /* An Mutex that the thread will wait/sleep on. */
95 /************************
99 * must hold at function call, return, sleep
100 * and resume from sleep.
112 * if read-locked without writers contending:
118 * if read-locked with writers contending:
121 * nwrite > 0 #writers blocked
127 * nwrite > 0 #writers blocked + 1
130 * To ensure consistency, state normally changes only while the
131 * thread changing it holds hThreadMutex.
135 char *name; /* The lock name, passed in at create time. */
136 HANDLE can_read; /* Manual event -- allows read locks */
137 HANDLE can_write; /* Auto-reset event -- allows write locks */
138 int nread; /* number of active readers */
139 int nwrite; /* total number of writers (active and waiting) */
142 /* This is the thread exclusion/non-premption mutex. */
143 /* The running thread has this MUTEX, and all others are */
144 /* either blocked on it, or waiting for some OS response. */
145 static HANDLE hThreadMutex;
147 /* This is the thread startup event. */
148 /* We use this to lockstep when we are starting up threads. */
149 static HANDLE hThreadStartEvent;
151 /* This is an event used to wakeup the main thread */
152 /* to start the shutdown sequence. */
153 static HANDLE hShutdownEvent;
155 /* The Thread Local Storage index. We store the pThread pointer */
156 /* for each thread at this index. */
157 static DWORD dwTLSIndex;
159 /* The current running thread. */
160 static empth_t *pCurThread;
163 static unsigned long ulTickAtStart;
165 /* Pointer out to global context. "player". */
166 /* From empth_init parameter. */
167 static void **ppvUserData;
169 /* Global flags. From empth_init parameter. */
170 static int global_flags;
172 static void loc_debug(const char *, ...) ATTRIBUTE((format(printf, 1, 2)));
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 if (pThread->szName != NULL)
225 free(pThread->szName);
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 hWaitObjects[0] = hThreadMutex;
245 hWaitObjects[1] = hWaitObject;
247 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
251 /* Set the globals to this thread. */
252 *ppvUserData = pThread->pvUserData;
254 pCurThread = pThread;
256 /* Hmm, a problem, eh? */
257 logerror("RunThisThread, someone already running.");
261 /************************
262 * loc_BlockThisThread
264 * This thread was running. It no longer wants to.
267 loc_BlockThisThread(void)
269 empth_t *pThread = TlsGetValue(dwTLSIndex);
271 if (pCurThread == pThread) {
272 /* Reset the globals back to original */
277 /* Release the MUTEX */
278 ReleaseMutex(hThreadMutex);
280 /* Hmm, this thread was not the running one. */
281 logerror("BlockThisThread, not running.");
285 /************************
288 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
289 * System-Shutdown will initiate a shutdown.
290 * This is done by calling empth_request_shutdown()
293 loc_Exit_Handler(DWORD fdwCtrlType)
295 switch (fdwCtrlType) {
297 case CTRL_CLOSE_EVENT:
298 case CTRL_BREAK_EVENT:
299 case CTRL_LOGOFF_EVENT:
300 case CTRL_SHUTDOWN_EVENT:
301 empth_request_shutdown();
308 /************************
311 * This is the main line of each thread.
312 * This is really a static local func....
313 * Note: As the POSIX compatibility layer is not thread safe
314 * this function can not open or create any files or sockets until
315 * loc_RunThisThread() is called
318 empth_threadMain(void *pvData)
320 empth_t *pThread = pvData;
326 /* Store pThread on this thread. */
327 TlsSetValue(dwTLSIndex, pvData);
329 /* Get the ID of the thread. */
330 pThread->ulThreadID = GetCurrentThreadId();
332 /* Signal that the thread has started. */
333 SetEvent(hThreadStartEvent);
335 /* Switch to this thread context */
336 loc_RunThisThread(NULL);
338 /* Run the thread. */
339 if (pThread->pfnEntry)
340 pThread->pfnEntry(pThread->pvUserData);
342 /* Kill the thread. */
346 /************************
349 * Initialize the thread environment.
351 * This is called from the program main line.
354 empth_init(void **ctx_ptr, int flags)
356 empth_t *pThread = NULL;
358 ulTickAtStart = GetTickCount();
359 ppvUserData = ctx_ptr;
360 global_flags = flags;
361 dwTLSIndex = TlsAlloc();
363 /* Create the thread mutex. */
364 /* Initally unowned. */
365 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
367 logerror("Failed to create mutex %lu", GetLastError());
371 /* Create the thread start event. */
372 /* Automatic state reset. */
373 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
374 if (!hThreadStartEvent) {
375 logerror("Failed to create start event %lu", GetLastError());
379 /* Create the shutdown event for the main thread. */
381 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
382 if (!hShutdownEvent) {
383 logerror("Failed to create shutdown event %lu", GetLastError());
386 SetConsoleCtrlHandler(loc_Exit_Handler, TRUE);
388 /* Create the global Thread context. */
389 pThread = malloc(sizeof(*pThread));
391 logerror("not enough memory to create main thread.");
394 memset(pThread, 0, sizeof(*pThread));
396 pThread->szName = strdup("Main");
397 pThread->ulThreadID = GetCurrentThreadId();
398 pThread->bMainThread = TRUE;
400 TlsSetValue(dwTLSIndex, pThread);
402 /* Make this the running thread. */
403 loc_RunThisThread(NULL);
405 logerror("NT pthreads initialized");
410 /************************
413 * Create a new thread.
415 * entry - entry point function for thread.
417 * flags - debug control.
418 * LWP_STACKCHECK - not needed
419 * name - name of the thread, for debug.
420 * ud - "user data". The "ctx_ptr" gets this value
421 * when the thread is active.
422 * It is also passed to the entry function...
425 empth_create(void (*entry)(void *), int size, int flags,
426 char *name, void *ud)
428 empth_t *pThread = NULL;
430 loc_debug("creating new thread %s", name);
432 pThread = malloc(sizeof(*pThread));
434 logerror("not enough memory to create thread %s", name);
437 memset(pThread, 0, sizeof(*pThread));
439 pThread->szName = strdup(name);
440 pThread->pvUserData = ud;
441 pThread->pfnEntry = entry;
442 pThread->bMainThread = FALSE;
444 /* Create thread event, auto reset. */
445 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
447 if (size < loc_MIN_THREAD_STACK)
448 size = loc_MIN_THREAD_STACK;
450 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
451 if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
452 logerror("can not create thread: %s: %s", name, strerror(errno));
456 loc_debug("new thread id is %ld", pThread->ulThreadID);
462 loc_FreeThreadInfo(pThread);
468 /************************
474 empth_t *pThread = TlsGetValue(dwTLSIndex);
479 /************************
483 empth_name(empth_t *thread)
485 return thread->szName;
488 /************************
490 * Set the thread name
493 empth_set_name(empth_t *thread, char *name)
495 if (thread->szName != NULL)
496 free(thread->szName);
497 thread->szName = strdup(name);
500 /************************
506 empth_t *pThread = TlsGetValue(dwTLSIndex);
508 loc_debug("empth_exit");
509 loc_BlockThisThread();
511 TlsSetValue(dwTLSIndex, NULL);
512 loc_FreeThreadInfo(pThread);
516 /************************
519 * Yield processing to another thread.
524 loc_BlockThisThread();
526 loc_RunThisThread(NULL);
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, struct timeval *timeout)
541 WSAEVENT hEventObject[2];
544 empth_t *pThread = TlsGetValue(dwTLSIndex);
547 loc_debug("%s select on %d",
548 flags == EMPTH_FD_READ ? "read" : "write", fd);
549 loc_BlockThisThread();
551 hEventObject[0] = WSACreateEvent();
552 hEventObject[1] = pThread->hThreadEvent;
554 handle = posix_fd2socket(fd);
555 CANT_HAPPEN(handle < 0);
558 if (flags & EMPTH_FD_READ)
559 events |= FD_READ | FD_ACCEPT | FD_CLOSE;
560 if (flags & EMPTH_FD_WRITE)
561 events |= FD_WRITE | FD_CLOSE;
562 WSAEventSelect(handle, hEventObject[0], events);
565 msec = timeout->tv_sec * 1000L + timeout->tv_usec / 1000L;
568 result = WSAWaitForMultipleEvents(2, hEventObject, FALSE, msec, FALSE);
571 case WSA_WAIT_TIMEOUT:
574 case WSA_WAIT_FAILED:
575 errno = WSAGetLastError();
582 WSAEventSelect(handle, hEventObject[0], 0);
584 WSACloseEvent(hEventObject[0]);
586 loc_RunThisThread(NULL);
590 /************************
593 * Wake up the specified thread.
596 empth_wakeup(empth_t *pThread)
598 loc_debug("waking up thread %s", pThread->szName);
600 /* Let it run if it is blocked... */
601 SetEvent(pThread->hThreadEvent);
604 /************************
607 * Put the given thread to sleep...
610 empth_sleep(time_t until)
614 empth_t *pThread = TlsGetValue(dwTLSIndex);
617 loc_BlockThisThread();
621 lSec = until >= now ? until - now : 0;
622 loc_debug("going to sleep %ld sec", lSec);
623 result = WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L);
624 } while (result != WAIT_TIMEOUT && result != WAIT_OBJECT_0);
626 loc_debug("sleep done. Waiting to run.");
627 loc_RunThisThread(NULL);
629 return result == WAIT_TIMEOUT ? 0 : -1;
632 /************************
633 * empth_request_shutdown
635 * This wakes up empth_wait_for_signal() so shutdown can proceed.
636 * This is done by signalling hShutdownEvent.
639 empth_request_shutdown(void)
641 SetEvent(hShutdownEvent);
645 empth_wait_for_signal(void)
647 loc_BlockThisThread();
648 loc_RunThisThread(hShutdownEvent);
653 empth_rwlock_create(char *name)
655 empth_rwlock_t *rwlock;
657 rwlock = malloc(sizeof(*rwlock));
661 memset(rwlock, 0, sizeof(*rwlock));
662 rwlock->name = strdup(name);
664 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
665 logerror("rwlock_create: failed to create reader event %s at %s:%d",
666 name, __FILE__, __LINE__);
672 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
673 logerror("rwlock_create: failed to create writer event %s at %s:%d",
674 name, __FILE__, __LINE__);
676 CloseHandle(rwlock->can_read);
684 empth_rwlock_destroy(empth_rwlock_t *rwlock)
686 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
688 if (rwlock->name != NULL)
690 CloseHandle(rwlock->can_read);
691 CloseHandle(rwlock->can_write);
696 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
698 /* block any new readers */
699 ResetEvent(rwlock->can_read);
701 loc_BlockThisThread();
702 loc_RunThisThread(rwlock->can_write);
703 CANT_HAPPEN(rwlock->nread != 0);
707 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
709 loc_BlockThisThread();
710 loc_RunThisThread(rwlock->can_read);
711 ResetEvent(rwlock->can_write);
716 empth_rwlock_unlock(empth_rwlock_t *rwlock)
718 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
720 if (rwlock->nread) { /* holding read lock */
722 if (rwlock->nread == 0)
723 SetEvent(rwlock->can_write);
726 SetEvent(rwlock->can_write);
728 if (rwlock->nwrite == 0)
729 SetEvent(rwlock->can_read);