2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
4 * Ken Stevens, Steve McClure, Markus Armbruster
6 * Empire 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 3 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, see <http://www.gnu.org/licenses/>.
21 * See files README, COPYING and CREDITS in the root of the source
22 * tree for related information and legal notices. It is expected
23 * that future projects/authors will amend these files as needed.
27 * ntthread.c: Interface from Empire threads to Windows NT threads
29 * Known contributors to this file:
32 * Ron Koenderink, 2004-2009
36 * EMPTHREADs for Windows NT.
38 * Actually, threads for any Win32 platform, like Win95, Win98, WinCE,
39 * and whatever other toy OSs are in our future from Microsoft.
41 * WIN32 has a full pre-emptive threading environment. But Empire can
42 * not handle pre-emptive threading. Thus, we will use the threads,
43 * but limit the preemption using a Mutex.
52 #include <sys/types.h>
57 #include "empthread.h"
59 #include "prototypes.h"
61 #include "sys/socket.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 /* The entry function for the thread. */
80 void (*pfnEntry) (void *);
82 /* The system thread ID. */
83 unsigned long ulThreadID;
85 /* An Mutex that the thread will wait/sleep on. */
90 /************************
94 * must hold at function call, return, sleep
95 * and resume from sleep.
107 * if read-locked without writers contending:
113 * if read-locked with writers contending:
116 * nwrite > 0 #writers blocked
122 * nwrite > 0 #writers blocked + 1
125 * To ensure consistency, state normally changes only while the
126 * thread changing it holds hThreadMutex.
130 char *name; /* The lock name, passed in at create time. */
131 HANDLE can_read; /* Manual event -- allows read locks */
132 HANDLE can_write; /* Auto-reset event -- allows write locks */
133 int nread; /* number of active readers */
134 int nwrite; /* total number of writers (active and waiting) */
137 /* This is the thread exclusion/non-premption mutex. */
138 /* The running thread has this MUTEX, and all others are */
139 /* either blocked on it, or waiting for some OS response. */
140 static HANDLE hThreadMutex;
142 /* This is the thread startup event. */
143 /* We use this to lockstep when we are starting up threads. */
144 static HANDLE hThreadStartEvent;
146 /* This is an event used to wakeup the main thread */
147 /* to start the shutdown sequence. */
148 static HANDLE hShutdownEvent;
150 /* The Thread Local Storage index. We store the pThread pointer */
151 /* for each thread at this index. */
152 static DWORD dwTLSIndex;
154 /* The current running thread. */
155 static empth_t *pCurThread;
158 static unsigned long ulTickAtStart;
160 /* Pointer out to global context. "player". */
161 /* From empth_init parameter. */
162 static void **ppvUserData;
164 /* Global flags. From empth_init parameter. */
165 static int global_flags;
167 static void loc_debug(const char *, ...) ATTRIBUTE((format(printf, 1, 2)));
169 /************************
172 * Print out the current thread's status??
175 loc_debug(const char *pszFmt, ...)
178 unsigned long ulCurTick;
179 unsigned long ulRunTick;
180 unsigned long ulMs, ulSec, ulMin, ulHr;
181 empth_t *pThread = TlsGetValue(dwTLSIndex);
184 if ((global_flags & EMPTH_PRINT) != 0) {
186 /* Ticks are in milliseconds */
187 ulCurTick = GetTickCount();
189 ulRunTick = ulCurTick - ulTickAtStart;
190 ulMs = ulRunTick % 1000L;
191 ulSec = (ulRunTick / 1000L) % 60L;
192 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
193 ulHr = (ulRunTick / (60L * 60L * 1000L));
195 va_start(vaList, pszFmt);
196 vsprintf(buf, pszFmt, vaList);
200 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
201 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
203 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
204 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
210 /************************
214 loc_FreeThreadInfo(empth_t *pThread)
217 if (pThread->hThreadEvent)
218 CloseHandle(pThread->hThreadEvent);
219 if (pThread->szName != NULL)
220 free(pThread->szName);
225 /************************
228 * This thread wants to run.
229 * When this function returns, the globals are set to this thread
230 * info, and the thread owns the MUTEX.
233 loc_RunThisThread(HANDLE hWaitObject)
235 HANDLE hWaitObjects[2];
237 empth_t *pThread = TlsGetValue(dwTLSIndex);
239 hWaitObjects[0] = hThreadMutex;
240 hWaitObjects[1] = hWaitObject;
242 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
246 /* Set the globals to this thread. */
247 *ppvUserData = pThread->pvUserData;
249 pCurThread = pThread;
251 /* Hmm, a problem, eh? */
252 logerror("RunThisThread, someone already running.");
256 /************************
257 * loc_BlockThisThread
259 * This thread was running. It no longer wants to.
262 loc_BlockThisThread(void)
264 empth_t *pThread = TlsGetValue(dwTLSIndex);
266 if (pCurThread == pThread) {
267 /* Reset the globals back to original */
272 /* Release the MUTEX */
273 ReleaseMutex(hThreadMutex);
275 /* Hmm, this thread was not the running one. */
276 logerror("BlockThisThread, not running.");
280 /************************
283 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
284 * System-Shutdown will initiate a shutdown.
285 * This is done by calling empth_request_shutdown()
288 loc_Exit_Handler(DWORD fdwCtrlType)
290 switch (fdwCtrlType) {
292 case CTRL_CLOSE_EVENT:
293 case CTRL_BREAK_EVENT:
294 case CTRL_LOGOFF_EVENT:
295 case CTRL_SHUTDOWN_EVENT:
296 empth_request_shutdown();
303 /************************
306 * This is the main line of each thread.
307 * This is really a static local func....
308 * Note: As the POSIX compatibility layer is not thread safe
309 * this function can not open or create any files or sockets until
310 * loc_RunThisThread() is called
313 empth_threadMain(void *pvData)
315 empth_t *pThread = pvData;
321 /* Store pThread on this thread. */
322 TlsSetValue(dwTLSIndex, pvData);
324 /* Get the ID of the thread. */
325 pThread->ulThreadID = GetCurrentThreadId();
327 /* Signal that the thread has started. */
328 SetEvent(hThreadStartEvent);
330 /* Switch to this thread context */
331 loc_RunThisThread(NULL);
333 /* Run the thread. */
334 if (pThread->pfnEntry)
335 pThread->pfnEntry(pThread->pvUserData);
337 /* Kill the thread. */
341 /************************
344 * Initialize the thread environment.
346 * This is called from the program main line.
349 empth_init(void **ctx_ptr, int flags)
351 empth_t *pThread = NULL;
353 ulTickAtStart = GetTickCount();
354 ppvUserData = ctx_ptr;
355 global_flags = flags;
356 dwTLSIndex = TlsAlloc();
358 /* Create the thread mutex. */
359 /* Initally unowned. */
360 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
362 logerror("Failed to create mutex %lu", GetLastError());
366 /* Create the thread start event. */
367 /* Automatic state reset. */
368 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
369 if (!hThreadStartEvent) {
370 logerror("Failed to create start event %lu", GetLastError());
374 /* Create the shutdown event for the main thread. */
376 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
377 if (!hShutdownEvent) {
378 logerror("Failed to create shutdown event %lu", GetLastError());
381 SetConsoleCtrlHandler(loc_Exit_Handler, TRUE);
383 /* Create the global Thread context. */
384 pThread = malloc(sizeof(*pThread));
386 logerror("not enough memory to create main thread.");
389 memset(pThread, 0, sizeof(*pThread));
391 pThread->szName = strdup("Main");
392 pThread->ulThreadID = GetCurrentThreadId();
393 pThread->bMainThread = TRUE;
395 TlsSetValue(dwTLSIndex, pThread);
397 /* Make this the running thread. */
398 loc_RunThisThread(NULL);
400 logerror("NT pthreads initialized");
405 /************************
408 * Create a new thread.
410 * entry - entry point function for thread.
412 * flags - debug control.
413 * LWP_STACKCHECK - not needed
414 * name - name of the thread, for debug.
415 * ud - "user data". The "ctx_ptr" gets this value
416 * when the thread is active.
417 * It is also passed to the entry function...
420 empth_create(void (*entry)(void *), int size, int flags,
421 char *name, void *ud)
423 empth_t *pThread = NULL;
425 loc_debug("creating new thread %s", name);
428 pThread = malloc(sizeof(*pThread));
430 logerror("not enough memory to create thread %s", name);
433 memset(pThread, 0, sizeof(*pThread));
435 pThread->szName = strdup(name);
436 pThread->pvUserData = ud;
437 pThread->pfnEntry = entry;
438 pThread->bMainThread = FALSE;
440 /* Create thread event, auto reset. */
441 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
443 if (size < loc_MIN_THREAD_STACK)
444 size = loc_MIN_THREAD_STACK;
446 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
447 if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
448 logerror("can not create thread: %s: %s", name, strerror(errno));
452 loc_debug("new thread id is %ld", pThread->ulThreadID);
458 loc_FreeThreadInfo(pThread);
464 /************************
470 empth_t *pThread = TlsGetValue(dwTLSIndex);
475 /************************
479 empth_name(empth_t *thread)
481 return thread->szName;
484 /************************
486 * Set the thread name
489 empth_set_name(empth_t *thread, char *name)
491 if (thread->szName != NULL)
492 free(thread->szName);
493 thread->szName = strdup(name);
496 /************************
502 empth_t *pThread = TlsGetValue(dwTLSIndex);
504 loc_debug("empth_exit");
506 loc_BlockThisThread();
508 TlsSetValue(dwTLSIndex, NULL);
509 loc_FreeThreadInfo(pThread);
513 /************************
516 * Yield processing to another thread.
522 loc_BlockThisThread();
524 loc_RunThisThread(NULL);
527 /************************
530 * Do a select on the given file.
533 * This would be one of the main functions used within gen\io.c
536 empth_select(int fd, int flags, struct timeval *timeout)
539 WSAEVENT hEventObject[2];
542 empth_t *pThread = TlsGetValue(dwTLSIndex);
545 loc_debug("%s select on %d",
546 flags == EMPTH_FD_READ ? "read" : "write", fd);
548 loc_BlockThisThread();
550 hEventObject[0] = WSACreateEvent();
551 hEventObject[1] = pThread->hThreadEvent;
553 sock = w32_fd2socket(fd);
554 CANT_HAPPEN(sock == (SOCKET)-1);
557 if (flags & EMPTH_FD_READ)
558 events |= FD_READ | FD_ACCEPT | FD_CLOSE;
559 if (flags & EMPTH_FD_WRITE)
560 events |= FD_WRITE | FD_CLOSE;
561 WSAEventSelect(sock, hEventObject[0], events);
564 msec = timeout->tv_sec * 1000L + timeout->tv_usec / 1000L;
567 result = WSAWaitForMultipleEvents(2, hEventObject, FALSE, msec, FALSE);
570 case WSA_WAIT_EVENT_0:
573 case WSA_WAIT_EVENT_0 + 1:
574 case WSA_WAIT_TIMEOUT:
577 case WSA_WAIT_FAILED:
578 w32_set_winsock_errno();
587 WSAEventSelect(sock, hEventObject[0], 0);
589 WSACloseEvent(hEventObject[0]);
591 loc_RunThisThread(NULL);
595 /************************
598 * Wake up the specified thread.
601 empth_wakeup(empth_t *pThread)
603 loc_debug("waking up thread %s", pThread->szName);
605 /* Let it run if it is blocked... */
606 SetEvent(pThread->hThreadEvent);
609 /************************
612 * Put the given thread to sleep...
615 empth_sleep(time_t until)
619 empth_t *pThread = TlsGetValue(dwTLSIndex);
623 loc_BlockThisThread();
627 lSec = until >= now ? until - now : 0;
628 loc_debug("going to sleep %ld sec", lSec);
629 result = WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L);
630 } while (result != WAIT_TIMEOUT && result != WAIT_OBJECT_0);
632 loc_debug("sleep done. Waiting to run.");
633 loc_RunThisThread(NULL);
635 return result == WAIT_TIMEOUT ? 0 : -1;
638 /************************
639 * empth_request_shutdown
641 * This wakes up empth_wait_for_signal() so shutdown can proceed.
642 * This is done by signalling hShutdownEvent.
645 empth_request_shutdown(void)
647 SetEvent(hShutdownEvent);
651 empth_wait_for_signal(void)
654 loc_BlockThisThread();
655 loc_RunThisThread(hShutdownEvent);
660 empth_rwlock_create(char *name)
662 empth_rwlock_t *rwlock;
664 rwlock = malloc(sizeof(*rwlock));
668 memset(rwlock, 0, sizeof(*rwlock));
669 rwlock->name = strdup(name);
671 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
672 logerror("rwlock_create: failed to create reader event %s at %s:%d",
673 name, __FILE__, __LINE__);
679 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
680 logerror("rwlock_create: failed to create writer event %s at %s:%d",
681 name, __FILE__, __LINE__);
683 CloseHandle(rwlock->can_read);
691 empth_rwlock_destroy(empth_rwlock_t *rwlock)
693 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
695 if (rwlock->name != NULL)
697 CloseHandle(rwlock->can_read);
698 CloseHandle(rwlock->can_write);
703 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
706 /* block any new readers */
707 ResetEvent(rwlock->can_read);
709 loc_BlockThisThread();
710 loc_RunThisThread(rwlock->can_write);
711 CANT_HAPPEN(rwlock->nread != 0);
715 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
718 loc_BlockThisThread();
719 loc_RunThisThread(rwlock->can_read);
720 ResetEvent(rwlock->can_write);
725 empth_rwlock_unlock(empth_rwlock_t *rwlock)
727 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
729 if (rwlock->nread) { /* holding read lock */
731 if (rwlock->nread == 0)
732 SetEvent(rwlock->can_write);
735 SetEvent(rwlock->can_write);
737 if (rwlock->nwrite == 0)
738 SetEvent(rwlock->can_read);