2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2014, 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);
404 /************************
407 * Create a new thread.
409 * entry - entry point function for thread.
411 * flags - debug control.
412 * LWP_STACKCHECK - not needed
413 * name - name of the thread, for debug.
414 * ud - "user data". The "ctx_ptr" gets this value
415 * when the thread is active.
416 * It is also passed to the entry function...
419 empth_create(void (*entry)(void *), int size, int flags,
420 char *name, void *ud)
422 empth_t *pThread = NULL;
424 loc_debug("creating new thread %s", name);
427 pThread = malloc(sizeof(*pThread));
429 logerror("not enough memory to create thread %s", name);
432 memset(pThread, 0, sizeof(*pThread));
434 pThread->szName = strdup(name);
435 pThread->pvUserData = ud;
436 pThread->pfnEntry = entry;
437 pThread->bMainThread = FALSE;
439 /* Create thread event, auto reset. */
440 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
442 if (size < loc_MIN_THREAD_STACK)
443 size = loc_MIN_THREAD_STACK;
445 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
446 if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
447 logerror("can not create thread: %s: %s", name, strerror(errno));
451 loc_debug("new thread id is %ld", pThread->ulThreadID);
457 loc_FreeThreadInfo(pThread);
463 /************************
469 return ppvUserData ? TlsGetValue(dwTLSIndex) : NULL;
472 /************************
476 empth_name(empth_t *thread)
478 return thread->szName;
481 /************************
483 * Set the thread name
486 empth_set_name(empth_t *thread, char *name)
488 if (thread->szName != NULL)
489 free(thread->szName);
490 thread->szName = strdup(name);
493 /************************
499 empth_t *pThread = TlsGetValue(dwTLSIndex);
501 loc_debug("empth_exit");
503 loc_BlockThisThread();
505 TlsSetValue(dwTLSIndex, NULL);
506 loc_FreeThreadInfo(pThread);
510 /************************
513 * Yield processing to another thread.
519 loc_BlockThisThread();
521 loc_RunThisThread(NULL);
524 /************************
527 * Do a select on the given file.
530 * This would be one of the main functions used within gen\io.c
533 empth_select(int fd, int flags, struct timeval *timeout)
536 WSAEVENT hEventObject[2];
539 empth_t *pThread = TlsGetValue(dwTLSIndex);
542 loc_debug("%s select on %d",
543 flags == EMPTH_FD_READ ? "read" : "write", fd);
545 loc_BlockThisThread();
547 hEventObject[0] = WSACreateEvent();
548 hEventObject[1] = pThread->hThreadEvent;
550 sock = w32_fd2socket(fd);
551 CANT_HAPPEN(sock == (SOCKET)-1);
554 if (flags & EMPTH_FD_READ)
555 events |= FD_READ | FD_ACCEPT | FD_CLOSE;
556 if (flags & EMPTH_FD_WRITE)
557 events |= FD_WRITE | FD_CLOSE;
558 WSAEventSelect(sock, hEventObject[0], events);
561 msec = timeout->tv_sec * 1000L + timeout->tv_usec / 1000L;
564 result = WSAWaitForMultipleEvents(2, hEventObject, FALSE, msec, FALSE);
567 case WSA_WAIT_EVENT_0:
570 case WSA_WAIT_EVENT_0 + 1:
571 case WSA_WAIT_TIMEOUT:
574 case WSA_WAIT_FAILED:
575 w32_set_winsock_errno();
584 WSAEventSelect(sock, hEventObject[0], 0);
586 WSACloseEvent(hEventObject[0]);
588 loc_RunThisThread(NULL);
592 /************************
595 * Wake up the specified thread.
598 empth_wakeup(empth_t *pThread)
600 loc_debug("waking up thread %s", pThread->szName);
602 /* Let it run if it is blocked... */
603 SetEvent(pThread->hThreadEvent);
606 /************************
609 * Put the given thread to sleep...
612 empth_sleep(time_t until)
616 empth_t *pThread = TlsGetValue(dwTLSIndex);
620 loc_BlockThisThread();
624 lSec = until >= now ? until - now : 0;
625 loc_debug("going to sleep %ld sec", lSec);
626 result = WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L);
627 } while (result != WAIT_TIMEOUT && result != WAIT_OBJECT_0);
629 loc_debug("sleep done. Waiting to run.");
630 loc_RunThisThread(NULL);
632 return result == WAIT_TIMEOUT ? 0 : -1;
635 /************************
636 * empth_request_shutdown
638 * This wakes up empth_wait_for_signal() so shutdown can proceed.
639 * This is done by signalling hShutdownEvent.
642 empth_request_shutdown(void)
644 SetEvent(hShutdownEvent);
648 empth_wait_for_signal(void)
651 loc_BlockThisThread();
652 loc_RunThisThread(hShutdownEvent);
657 empth_rwlock_create(char *name)
659 empth_rwlock_t *rwlock;
661 rwlock = malloc(sizeof(*rwlock));
665 memset(rwlock, 0, sizeof(*rwlock));
666 rwlock->name = strdup(name);
668 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
669 logerror("rwlock_create: failed to create reader event %s at %s:%d",
670 name, __FILE__, __LINE__);
676 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
677 logerror("rwlock_create: failed to create writer event %s at %s:%d",
678 name, __FILE__, __LINE__);
680 CloseHandle(rwlock->can_read);
688 empth_rwlock_destroy(empth_rwlock_t *rwlock)
690 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
692 if (rwlock->name != NULL)
694 CloseHandle(rwlock->can_read);
695 CloseHandle(rwlock->can_write);
700 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
703 /* block any new readers */
704 ResetEvent(rwlock->can_read);
706 loc_BlockThisThread();
707 loc_RunThisThread(rwlock->can_write);
708 CANT_HAPPEN(rwlock->nread != 0);
712 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
715 loc_BlockThisThread();
716 loc_RunThisThread(rwlock->can_read);
717 ResetEvent(rwlock->can_write);
722 empth_rwlock_unlock(empth_rwlock_t *rwlock)
724 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
726 if (rwlock->nread) { /* holding read lock */
728 if (rwlock->nread == 0)
729 SetEvent(rwlock->can_write);
732 SetEvent(rwlock->can_write);
734 if (rwlock->nwrite == 0)
735 SetEvent(rwlock->can_read);