2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2008, 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.
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 /* True if this thread has been killed. */
87 /* The entry function for the thread. */
88 void (*pfnEntry) (void *);
90 /* The system thread ID. */
91 unsigned long ulThreadID;
93 /* An Mutex that the thread will wait/sleep on. */
98 /************************
102 * must hold at function call, return, sleep
103 * and resume from sleep.
115 * if read-locked without writers contending:
121 * if read-locked with writers contending:
124 * nwrite > 0 #writers blocked
130 * nwrite > 0 #writers blocked + 1
133 * To ensure consistency, state normally changes only while the
134 * thread changing it holds hThreadMutex.
138 char name[17]; /* The thread name, passed in at create time. */
139 HANDLE can_read; /* Manual event -- allows read locks */
140 HANDLE can_write; /* Auto-reset event -- allows write locks */
141 int nread; /* number of active readers */
142 int nwrite; /* total number of writers (active and waiting) */
145 /* This is the thread exclusion/non-premption mutex. */
146 /* The running thread has this MUTEX, and all others are */
147 /* either blocked on it, or waiting for some OS response. */
148 static HANDLE hThreadMutex;
150 /* This is the thread startup event. */
151 /* We use this to lockstep when we are starting up threads. */
152 static HANDLE hThreadStartEvent;
154 /* This is an event used to wakeup the main thread */
155 /* to start the shutdown sequence. */
156 static HANDLE hShutdownEvent;
158 /* The Thread Local Storage index. We store the pThread pointer */
159 /* for each thread at this index. */
160 static DWORD dwTLSIndex;
162 /* The current running thread. */
163 static empth_t *pCurThread;
166 static unsigned long ulTickAtStart;
168 /* Pointer out to global context. "player". */
169 /* From empth_init parameter. */
170 static void **ppvUserData;
172 /* Global flags. From empth_init parameter. */
173 static int global_flags;
176 /************************
179 * Print out the current thread's status??
182 loc_debug(const char *pszFmt, ...)
185 unsigned long ulCurTick;
186 unsigned long ulRunTick;
187 unsigned long ulMs, ulSec, ulMin, ulHr;
188 empth_t *pThread = TlsGetValue(dwTLSIndex);
191 if ((global_flags & EMPTH_PRINT) != 0) {
193 /* Ticks are in milliseconds */
194 ulCurTick = GetTickCount();
196 ulRunTick = ulCurTick - ulTickAtStart;
197 ulMs = ulRunTick % 1000L;
198 ulSec = (ulRunTick / 1000L) % 60L;
199 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
200 ulHr = (ulRunTick / (60L * 60L * 1000L));
202 va_start(vaList, pszFmt);
203 vsprintf(buf, pszFmt, vaList);
207 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
208 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
210 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
211 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
217 /************************
221 loc_FreeThreadInfo(empth_t *pThread)
224 if (pThread->hThreadEvent)
225 CloseHandle(pThread->hThreadEvent);
226 memset(pThread, 0, sizeof(*pThread));
231 /************************
234 * This thread wants to run.
235 * When this function returns, the globals are set to this thread
236 * info, and the thread owns the MUTEX.
239 loc_RunThisThread(HANDLE hWaitObject)
241 HANDLE hWaitObjects[2];
243 empth_t *pThread = TlsGetValue(dwTLSIndex);
245 if (pThread->bKilled) {
246 if (!pThread->bMainThread) {
247 TlsSetValue(dwTLSIndex, NULL);
248 loc_FreeThreadInfo(pThread);
253 hWaitObjects[0] = hThreadMutex;
254 hWaitObjects[1] = hWaitObject;
256 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
260 /* Set the globals to this thread. */
261 *ppvUserData = pThread->pvUserData;
263 pCurThread = pThread;
265 /* Hmm, a problem, eh? */
266 logerror("RunThisThread, someone already running.");
270 /************************
271 * loc_BlockThisThread
273 * This thread was running. It no longer wants to.
276 loc_BlockThisThread(void)
278 empth_t *pThread = TlsGetValue(dwTLSIndex);
280 if (pCurThread == pThread) {
281 /* Reset the globals back to original */
286 /* Release the MUTEX */
287 ReleaseMutex(hThreadMutex);
289 /* Hmm, this thread was not the running one. */
290 logerror("BlockThisThread, not running.");
294 /************************
297 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
298 * System-Shutdown will initiate a shutdown.
299 * This is done by calling empth_request_shutdown()
302 loc_Exit_Handler(DWORD fdwCtrlType)
304 switch (fdwCtrlType) {
306 case CTRL_CLOSE_EVENT:
307 case CTRL_BREAK_EVENT:
308 case CTRL_LOGOFF_EVENT:
309 case CTRL_SHUTDOWN_EVENT:
310 empth_request_shutdown();
317 /************************
320 * This is the main line of each thread.
321 * This is really a static local func....
322 * Note: As the POSIX compatibility layer is not thread safe
323 * this function can not open or create any files or sockets until
324 * loc_RunThisThread() is called
327 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 /* Switch to this thread context */
345 loc_RunThisThread(NULL);
347 /* Run the thread. */
348 if (pThread->pfnEntry)
349 pThread->pfnEntry(pThread->pvUserData);
351 /* Kill the thread. */
355 /************************
358 * Initialize the thread environment.
360 * This is called from the program main line.
363 empth_init(void **ctx_ptr, int flags)
365 empth_t *pThread = NULL;
367 ulTickAtStart = GetTickCount();
368 ppvUserData = ctx_ptr;
369 global_flags = flags;
370 dwTLSIndex = TlsAlloc();
372 /* Create the thread mutex. */
373 /* Initally unowned. */
374 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
376 logerror("Failed to create mutex %lu", GetLastError());
380 /* Create the thread start event. */
381 /* Automatic state reset. */
382 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
383 if (!hThreadStartEvent) {
384 logerror("Failed to create start event %lu", GetLastError());
388 /* Create the shutdown event for the main thread. */
390 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
391 if (!hShutdownEvent) {
392 logerror("Failed to create shutdown event %lu", GetLastError());
395 SetConsoleCtrlHandler(loc_Exit_Handler, TRUE);
397 /* Create the global Thread context. */
398 pThread = malloc(sizeof(*pThread));
400 logerror("not enough memory to create main thread.");
403 memset(pThread, 0, sizeof(*pThread));
405 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
406 pThread->ulThreadID = GetCurrentThreadId();
407 pThread->bMainThread = TRUE;
409 TlsSetValue(dwTLSIndex, pThread);
411 /* Make this the running thread. */
412 loc_RunThisThread(NULL);
414 logerror("NT pthreads initialized");
419 /************************
422 * Create a new thread.
424 * entry - entry point function for thread.
426 * flags - debug control.
427 * LWP_STACKCHECK - not needed
428 * name - name of the thread, for debug.
429 * ud - "user data". The "ctx_ptr" gets this value
430 * when the thread is active.
431 * It is also passed to the entry function...
434 empth_create(void (*entry)(void *), int size, int flags,
435 char *name, void *ud)
437 empth_t *pThread = NULL;
439 loc_debug("creating new thread %s", name);
441 pThread = malloc(sizeof(*pThread));
443 logerror("not enough memory to create thread %s", name);
446 memset(pThread, 0, sizeof(*pThread));
448 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
449 pThread->pvUserData = ud;
450 pThread->pfnEntry = entry;
451 pThread->bMainThread = FALSE;
453 /* Create thread event, auto reset. */
454 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
456 if (size < loc_MIN_THREAD_STACK)
457 size = loc_MIN_THREAD_STACK;
459 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
460 if (pThread->ulThreadID == 1L) {
461 logerror("can not create thread: %s: %s", name, strerror(errno));
465 loc_debug("new thread id is %ld", pThread->ulThreadID);
471 loc_FreeThreadInfo(pThread);
477 /************************
483 empth_t *pThread = TlsGetValue(dwTLSIndex);
488 /************************
494 empth_t *pThread = TlsGetValue(dwTLSIndex);
496 loc_debug("empth_exit");
497 loc_BlockThisThread();
499 TlsSetValue(dwTLSIndex, NULL);
500 loc_FreeThreadInfo(pThread);
504 /************************
507 * Yield processing to another thread.
512 loc_BlockThisThread();
513 loc_RunThisThread(NULL);
516 /************************
519 * Kill off the thread.
522 empth_terminate(empth_t *pThread)
524 loc_debug("killing thread %s", pThread->szName);
525 pThread->bKilled = TRUE;
527 SetEvent(pThread->hThreadEvent);
530 /************************
533 * Do a select on the given file.
536 * This would be one of the main functions used within gen\io.c
539 empth_select(int fd, int flags)
542 WSAEVENT hEventObject[2];
543 empth_t *pThread = TlsGetValue(dwTLSIndex);
545 loc_debug("%s select on %d",
546 flags == EMPTH_FD_READ ? "read" : "write", fd);
547 loc_BlockThisThread();
549 hEventObject[0] = WSACreateEvent();
550 hEventObject[1] = pThread->hThreadEvent;
552 handle = posix_fd2socket(fd);
553 CANT_HAPPEN(handle < 0);
555 if (flags == EMPTH_FD_READ)
556 WSAEventSelect(handle, hEventObject[0], FD_READ | FD_ACCEPT | FD_CLOSE);
557 else if (flags == EMPTH_FD_WRITE)
558 WSAEventSelect(handle, hEventObject[0], FD_WRITE | FD_CLOSE);
560 logerror("bad flag %d passed to empth_select", flags);
564 WSAWaitForMultipleEvents(2, hEventObject, FALSE, WSA_INFINITE, FALSE);
566 WSAEventSelect(handle, hEventObject[0], 0);
568 WSACloseEvent(hEventObject[0]);
570 loc_RunThisThread(NULL);
573 /************************
576 * Wake up the specified thread.
579 empth_wakeup(empth_t *pThread)
581 loc_debug("waking up thread %s", pThread->szName);
583 /* Let it run if it is blocked... */
584 SetEvent(pThread->hThreadEvent);
587 /************************
590 * Put the given thread to sleep...
593 empth_sleep(time_t until)
596 empth_t *pThread = TlsGetValue(dwTLSIndex);
599 while (!iReturn && ((lSec = until - time(0)) > 0)) {
600 loc_BlockThisThread();
601 loc_debug("going to sleep %ld sec", lSec);
603 if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
607 loc_debug("sleep done. Waiting to run.");
608 loc_RunThisThread(NULL);
613 /************************
614 * empth_request_shutdown
616 * This wakes up empth_wait_for_signal() so shutdown can proceed.
617 * This is done by signalling hShutdownEvent.
620 empth_request_shutdown(void)
622 SetEvent(hShutdownEvent);
626 empth_wait_for_signal(void)
628 loc_BlockThisThread();
629 loc_RunThisThread(hShutdownEvent);
634 empth_rwlock_create(char *name)
636 empth_rwlock_t *rwlock;
638 rwlock = malloc(sizeof(*rwlock));
642 memset(rwlock, 0, sizeof(*rwlock));
643 strncpy(rwlock->name, name, sizeof(rwlock->name) - 1);
645 if ((rwlock->can_read = CreateEvent(NULL, TRUE, TRUE, NULL)) == NULL) {
646 logerror("rwlock_create: failed to create reader event %s at %s:%d",
647 name, __FILE__, __LINE__);
652 if ((rwlock->can_write = CreateEvent(NULL, FALSE, TRUE, NULL)) == NULL) {
653 logerror("rwlock_create: failed to create writer event %s at %s:%d",
654 name, __FILE__, __LINE__);
655 CloseHandle(rwlock->can_read);
663 empth_rwlock_destroy(empth_rwlock_t *rwlock)
665 if (CANT_HAPPEN(rwlock->nread || rwlock->nwrite))
667 CloseHandle(rwlock->can_read);
668 CloseHandle(rwlock->can_write);
673 empth_rwlock_wrlock(empth_rwlock_t *rwlock)
675 /* block any new readers */
676 ResetEvent(rwlock->can_read);
678 loc_BlockThisThread();
679 loc_RunThisThread(rwlock->can_write);
680 CANT_HAPPEN(rwlock->nread != 0);
684 empth_rwlock_rdlock(empth_rwlock_t *rwlock)
686 loc_BlockThisThread();
687 loc_RunThisThread(rwlock->can_read);
688 ResetEvent(rwlock->can_write);
693 empth_rwlock_unlock(empth_rwlock_t *rwlock)
695 if (CANT_HAPPEN(!rwlock->nread && !rwlock->nwrite))
697 if (rwlock->nread) { /* holding read lock */
699 if (rwlock->nread == 0)
700 SetEvent(rwlock->can_write);
703 SetEvent(rwlock->can_write);
705 if (rwlock->nwrite == 0)
706 SetEvent(rwlock->can_read);