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>
58 #include "empthread.h"
60 #include "prototypes.h"
62 #include "sys/socket.h"
64 #define loc_MIN_THREAD_STACK 16384
66 /************************
71 /* The thread name, passed in at create time. */
74 /* True if this is the main line, and not a real thread. */
77 /* The user data passed in at create time. */
80 /* The entry function for the thread. */
81 void (*pfnEntry) (void *);
83 /* The system thread ID. */
84 unsigned long ulThreadID;
86 /* An Mutex that the thread will wait/sleep on. */
91 /************************
95 * must hold at function call, return, sleep
96 * and resume from sleep.
108 * if read-locked without writers contending:
114 * if read-locked with writers contending:
117 * nwrite > 0 #writers blocked
123 * nwrite > 0 #writers blocked + 1
126 * To ensure consistency, state normally changes only while the
127 * thread changing it holds hThreadMutex.
131 char *name; /* The lock name, passed in at create time. */
132 HANDLE can_read; /* Manual event -- allows read locks */
133 HANDLE can_write; /* Auto-reset event -- allows write locks */
134 int nread; /* number of active readers */
135 int nwrite; /* total number of writers (active and waiting) */
138 /* This is the thread exclusion/non-premption mutex. */
139 /* The running thread has this MUTEX, and all others are */
140 /* either blocked on it, or waiting for some OS response. */
141 static HANDLE hThreadMutex;
143 /* This is the thread startup event. */
144 /* We use this to lockstep when we are starting up threads. */
145 static HANDLE hThreadStartEvent;
147 /* This is an event used to wakeup the main thread */
148 /* to start the shutdown sequence. */
149 static HANDLE hShutdownEvent;
151 /* The Thread Local Storage index. We store the pThread pointer */
152 /* for each thread at this index. */
153 static DWORD dwTLSIndex;
155 /* The current running thread. */
156 static empth_t *pCurThread;
159 static unsigned long ulTickAtStart;
161 /* Pointer out to global context. "player". */
162 /* From empth_init parameter. */
163 static void **ppvUserData;
165 /* Global flags. From empth_init parameter. */
166 static int global_flags;
168 static void loc_debug(const char *, ...) ATTRIBUTE((format(printf, 1, 2)));
170 /************************
173 * Print out the current thread's status??
176 loc_debug(const char *pszFmt, ...)
179 unsigned long ulCurTick;
180 unsigned long ulRunTick;
181 unsigned long ulMs, ulSec, ulMin, ulHr;
182 empth_t *pThread = TlsGetValue(dwTLSIndex);
185 if ((global_flags & EMPTH_PRINT) != 0) {
187 /* Ticks are in milliseconds */
188 ulCurTick = GetTickCount();
190 ulRunTick = ulCurTick - ulTickAtStart;
191 ulMs = ulRunTick % 1000L;
192 ulSec = (ulRunTick / 1000L) % 60L;
193 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
194 ulHr = (ulRunTick / (60L * 60L * 1000L));
196 va_start(vaList, pszFmt);
197 vsprintf(buf, pszFmt, vaList);
201 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
202 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
204 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
205 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
211 /************************
215 loc_FreeThreadInfo(empth_t *pThread)
218 if (pThread->hThreadEvent)
219 CloseHandle(pThread->hThreadEvent);
220 if (pThread->szName != NULL)
221 free(pThread->szName);
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 hWaitObjects[0] = hThreadMutex;
241 hWaitObjects[1] = hWaitObject;
243 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
247 /* Set the globals to this thread. */
248 *ppvUserData = pThread->pvUserData;
250 pCurThread = pThread;
252 /* Hmm, a problem, eh? */
253 logerror("RunThisThread, someone already running.");
257 /************************
258 * loc_BlockThisThread
260 * This thread was running. It no longer wants to.
263 loc_BlockThisThread(void)
265 empth_t *pThread = TlsGetValue(dwTLSIndex);
267 if (pCurThread == pThread) {
268 /* Reset the globals back to original */
273 /* Release the MUTEX */
274 ReleaseMutex(hThreadMutex);
276 /* Hmm, this thread was not the running one. */
277 logerror("BlockThisThread, not running.");
281 /************************
284 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
285 * System-Shutdown will initiate a shutdown.
286 * This is done by calling empth_request_shutdown()
289 loc_Exit_Handler(DWORD fdwCtrlType)
291 switch (fdwCtrlType) {
293 case CTRL_CLOSE_EVENT:
294 case CTRL_BREAK_EVENT:
295 case CTRL_LOGOFF_EVENT:
296 case CTRL_SHUTDOWN_EVENT:
297 empth_request_shutdown();
304 /************************
307 * This is the main line of each thread.
308 * This is really a static local func....
309 * Note: As the POSIX compatibility layer is not thread safe
310 * this function can not open or create any files or sockets until
311 * loc_RunThisThread() is called
314 empth_threadMain(void *pvData)
316 empth_t *pThread = pvData;
322 /* Store pThread on this thread. */
323 TlsSetValue(dwTLSIndex, pvData);
325 /* Get the ID of the thread. */
326 pThread->ulThreadID = GetCurrentThreadId();
328 /* Signal that the thread has started. */
329 SetEvent(hThreadStartEvent);
331 /* Switch to this thread context */
332 loc_RunThisThread(NULL);
334 /* Run the thread. */
335 if (pThread->pfnEntry)
336 pThread->pfnEntry(pThread->pvUserData);
338 /* Kill the thread. */
342 /************************
345 * Initialize the thread environment.
347 * This is called from the program main line.
350 empth_init(void **ctx_ptr, int flags)
352 empth_t *pThread = NULL;
354 ulTickAtStart = GetTickCount();
355 ppvUserData = ctx_ptr;
356 global_flags = flags;
357 dwTLSIndex = TlsAlloc();
359 /* Create the thread mutex. */
360 /* Initally unowned. */
361 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
363 logerror("Failed to create mutex %lu", GetLastError());
367 /* Create the thread start event. */
368 /* Automatic state reset. */
369 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
370 if (!hThreadStartEvent) {
371 logerror("Failed to create start event %lu", GetLastError());
375 /* Create the shutdown event for the main thread. */
377 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
378 if (!hShutdownEvent) {
379 logerror("Failed to create shutdown event %lu", GetLastError());
382 SetConsoleCtrlHandler(loc_Exit_Handler, TRUE);
384 /* Create the global Thread context. */
385 pThread = malloc(sizeof(*pThread));
387 logerror("not enough memory to create main thread.");
390 memset(pThread, 0, sizeof(*pThread));
392 pThread->szName = strdup("Main");
393 pThread->ulThreadID = GetCurrentThreadId();
394 pThread->bMainThread = TRUE;
396 TlsSetValue(dwTLSIndex, pThread);
398 /* Make this the running thread. */
399 loc_RunThisThread(NULL);
401 logerror("NT pthreads initialized");
406 /************************
409 * Create a new thread.
411 * entry - entry point function for thread.
413 * flags - debug control.
414 * LWP_STACKCHECK - not needed
415 * name - name of the thread, for debug.
416 * ud - "user data". The "ctx_ptr" gets this value
417 * when the thread is active.
418 * It is also passed to the entry function...
421 empth_create(void (*entry)(void *), int size, int flags,
422 char *name, void *ud)
424 empth_t *pThread = NULL;
426 loc_debug("creating new thread %s", name);
429 pThread = malloc(sizeof(*pThread));
431 logerror("not enough memory to create thread %s", name);
434 memset(pThread, 0, sizeof(*pThread));
436 pThread->szName = strdup(name);
437 pThread->pvUserData = ud;
438 pThread->pfnEntry = entry;
439 pThread->bMainThread = FALSE;
441 /* Create thread event, auto reset. */
442 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
444 if (size < loc_MIN_THREAD_STACK)
445 size = loc_MIN_THREAD_STACK;
447 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
448 if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
449 logerror("can not create thread: %s: %s", name, strerror(errno));
453 loc_debug("new thread id is %ld", pThread->ulThreadID);
459 loc_FreeThreadInfo(pThread);
465 /************************
471 empth_t *pThread = TlsGetValue(dwTLSIndex);
476 /************************
480 empth_name(empth_t *thread)
482 return thread->szName;
485 /************************
487 * Set the thread name
490 empth_set_name(empth_t *thread, char *name)
492 if (thread->szName != NULL)
493 free(thread->szName);
494 thread->szName = strdup(name);
497 /************************
503 empth_t *pThread = TlsGetValue(dwTLSIndex);
505 loc_debug("empth_exit");
507 loc_BlockThisThread();
509 TlsSetValue(dwTLSIndex, NULL);
510 loc_FreeThreadInfo(pThread);
514 /************************
517 * Yield processing to another thread.
523 loc_BlockThisThread();
525 loc_RunThisThread(NULL);
528 /************************
531 * Do a select on the given file.
534 * This would be one of the main functions used within gen\io.c
537 empth_select(int fd, int flags, struct timeval *timeout)
540 WSAEVENT hEventObject[2];
543 empth_t *pThread = TlsGetValue(dwTLSIndex);
546 loc_debug("%s select on %d",
547 flags == EMPTH_FD_READ ? "read" : "write", fd);
549 loc_BlockThisThread();
551 hEventObject[0] = WSACreateEvent();
552 hEventObject[1] = pThread->hThreadEvent;
554 sock = w32_fd2socket(fd);
555 CANT_HAPPEN(sock == (SOCKET)-1);
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(sock, 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_EVENT_0:
574 case WSA_WAIT_EVENT_0 + 1:
575 case WSA_WAIT_TIMEOUT:
578 case WSA_WAIT_FAILED:
579 w32_set_winsock_errno();
588 WSAEventSelect(sock, hEventObject[0], 0);
590 WSACloseEvent(hEventObject[0]);
592 loc_RunThisThread(NULL);
596 /************************
599 * Wake up the specified thread.
602 empth_wakeup(empth_t *pThread)
604 loc_debug("waking up thread %s", pThread->szName);
606 /* Let it run if it is blocked... */
607 SetEvent(pThread->hThreadEvent);
610 /************************
613 * Put the given thread to sleep...
616 empth_sleep(time_t until)
620 empth_t *pThread = TlsGetValue(dwTLSIndex);
624 loc_BlockThisThread();
628 lSec = until >= now ? until - now : 0;
629 loc_debug("going to sleep %ld sec", lSec);
630 result = WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L);
631 } while (result != WAIT_TIMEOUT && result != WAIT_OBJECT_0);
633 loc_debug("sleep done. Waiting to run.");
634 loc_RunThisThread(NULL);
636 return result == WAIT_TIMEOUT ? 0 : -1;
639 /************************
640 * empth_request_shutdown
642 * This wakes up empth_wait_for_signal() so shutdown can proceed.
643 * This is done by signalling hShutdownEvent.
646 empth_request_shutdown(void)
648 SetEvent(hShutdownEvent);
652 empth_wait_for_signal(void)
655 loc_BlockThisThread();
656 loc_RunThisThread(hShutdownEvent);
661 empth_rwlock_create(char *name)
663 empth_rwlock_t *rwlock;
665 rwlock = malloc(sizeof(*rwlock));
669 memset(rwlock, 0, sizeof(*rwlock));
670 rwlock->name = strdup(name);
672 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
673 logerror("rwlock_create: failed to create reader event %s at %s:%d",
674 name, __FILE__, __LINE__);
680 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
681 logerror("rwlock_create: failed to create writer event %s at %s:%d",
682 name, __FILE__, __LINE__);
684 CloseHandle(rwlock->can_read);
692 empth_rwlock_destroy(empth_rwlock_t *rwlock)
694 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
696 if (rwlock->name != NULL)
698 CloseHandle(rwlock->can_read);
699 CloseHandle(rwlock->can_write);
704 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
707 /* block any new readers */
708 ResetEvent(rwlock->can_read);
710 loc_BlockThisThread();
711 loc_RunThisThread(rwlock->can_write);
712 CANT_HAPPEN(rwlock->nread != 0);
716 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
719 loc_BlockThisThread();
720 loc_RunThisThread(rwlock->can_read);
721 ResetEvent(rwlock->can_write);
726 empth_rwlock_unlock(empth_rwlock_t *rwlock)
728 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
730 if (rwlock->nread) { /* holding read lock */
732 if (rwlock->nread == 0)
733 SetEvent(rwlock->can_write);
736 SetEvent(rwlock->can_write);
738 if (rwlock->nwrite == 0)
739 SetEvent(rwlock->can_read);