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);
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 hWaitObjects[0] = hThreadMutex;
246 hWaitObjects[1] = hWaitObject;
248 WaitForMultipleObjects(hWaitObject ? 2 : 1, hWaitObjects,
252 /* Set the globals to this thread. */
253 *ppvUserData = pThread->pvUserData;
255 pCurThread = pThread;
257 /* Hmm, a problem, eh? */
258 logerror("RunThisThread, someone already running.");
262 /************************
263 * loc_BlockThisThread
265 * This thread was running. It no longer wants to.
268 loc_BlockThisThread(void)
270 empth_t *pThread = TlsGetValue(dwTLSIndex);
272 if (pCurThread == pThread) {
273 /* Reset the globals back to original */
278 /* Release the MUTEX */
279 ReleaseMutex(hThreadMutex);
281 /* Hmm, this thread was not the running one. */
282 logerror("BlockThisThread, not running.");
286 /************************
289 * Ctrl-C, Ctrl-Break, Window-Closure, User-Logging-Off or
290 * System-Shutdown will initiate a shutdown.
291 * This is done by calling empth_request_shutdown()
294 loc_Exit_Handler(DWORD fdwCtrlType)
296 switch (fdwCtrlType) {
298 case CTRL_CLOSE_EVENT:
299 case CTRL_BREAK_EVENT:
300 case CTRL_LOGOFF_EVENT:
301 case CTRL_SHUTDOWN_EVENT:
302 empth_request_shutdown();
309 /************************
312 * This is the main line of each thread.
313 * This is really a static local func....
314 * Note: As the POSIX compatibility layer is not thread safe
315 * this function can not open or create any files or sockets until
316 * loc_RunThisThread() is called
319 empth_threadMain(void *pvData)
321 empth_t *pThread = pvData;
327 /* Store pThread on this thread. */
328 TlsSetValue(dwTLSIndex, pvData);
330 /* Get the ID of the thread. */
331 pThread->ulThreadID = GetCurrentThreadId();
333 /* Signal that the thread has started. */
334 SetEvent(hThreadStartEvent);
336 /* Switch to this thread context */
337 loc_RunThisThread(NULL);
339 /* Run the thread. */
340 if (pThread->pfnEntry)
341 pThread->pfnEntry(pThread->pvUserData);
343 /* Kill the thread. */
347 /************************
350 * Initialize the thread environment.
352 * This is called from the program main line.
355 empth_init(void **ctx_ptr, int flags)
357 empth_t *pThread = NULL;
359 ulTickAtStart = GetTickCount();
360 ppvUserData = ctx_ptr;
361 global_flags = flags;
362 dwTLSIndex = TlsAlloc();
364 /* Create the thread mutex. */
365 /* Initally unowned. */
366 hThreadMutex = CreateMutex(NULL, FALSE, NULL);
368 logerror("Failed to create mutex %lu", GetLastError());
372 /* Create the thread start event. */
373 /* Automatic state reset. */
374 hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
375 if (!hThreadStartEvent) {
376 logerror("Failed to create start event %lu", GetLastError());
380 /* Create the shutdown event for the main thread. */
382 hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
383 if (!hShutdownEvent) {
384 logerror("Failed to create shutdown event %lu", GetLastError());
387 SetConsoleCtrlHandler(loc_Exit_Handler, TRUE);
389 /* Create the global Thread context. */
390 pThread = malloc(sizeof(*pThread));
392 logerror("not enough memory to create main thread.");
395 memset(pThread, 0, sizeof(*pThread));
397 pThread->szName = strdup("Main");
398 pThread->ulThreadID = GetCurrentThreadId();
399 pThread->bMainThread = TRUE;
401 TlsSetValue(dwTLSIndex, pThread);
403 /* Make this the running thread. */
404 loc_RunThisThread(NULL);
406 logerror("NT pthreads initialized");
411 /************************
414 * Create a new thread.
416 * entry - entry point function for thread.
418 * flags - debug control.
419 * LWP_STACKCHECK - not needed
420 * name - name of the thread, for debug.
421 * ud - "user data". The "ctx_ptr" gets this value
422 * when the thread is active.
423 * It is also passed to the entry function...
426 empth_create(void (*entry)(void *), int size, int flags,
427 char *name, void *ud)
429 empth_t *pThread = NULL;
431 loc_debug("creating new thread %s", name);
433 pThread = malloc(sizeof(*pThread));
435 logerror("not enough memory to create thread %s", name);
438 memset(pThread, 0, sizeof(*pThread));
440 pThread->szName = strdup(name);
441 pThread->pvUserData = ud;
442 pThread->pfnEntry = entry;
443 pThread->bMainThread = FALSE;
445 /* Create thread event, auto reset. */
446 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
448 if (size < loc_MIN_THREAD_STACK)
449 size = loc_MIN_THREAD_STACK;
451 pThread->ulThreadID = _beginthread(empth_threadMain, size, pThread);
452 if (pThread->ulThreadID == 1L || pThread->ulThreadID == 0L) {
453 logerror("can not create thread: %s: %s", name, strerror(errno));
457 loc_debug("new thread id is %ld", pThread->ulThreadID);
463 loc_FreeThreadInfo(pThread);
469 /************************
475 empth_t *pThread = TlsGetValue(dwTLSIndex);
480 /************************
484 empth_name(empth_t *thread)
486 return thread->szName;
489 /************************
491 * Set the thread name
494 empth_set_name(empth_t *thread, char *name)
496 if (thread->szName != NULL)
497 free(thread->szName);
498 thread->szName = strdup(name);
501 /************************
507 empth_t *pThread = TlsGetValue(dwTLSIndex);
509 loc_debug("empth_exit");
510 loc_BlockThisThread();
512 TlsSetValue(dwTLSIndex, NULL);
513 loc_FreeThreadInfo(pThread);
517 /************************
520 * Yield processing to another thread.
525 loc_BlockThisThread();
527 loc_RunThisThread(NULL);
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, struct timeval *timeout)
542 WSAEVENT hEventObject[2];
545 empth_t *pThread = TlsGetValue(dwTLSIndex);
548 loc_debug("%s select on %d",
549 flags == EMPTH_FD_READ ? "read" : "write", fd);
550 loc_BlockThisThread();
552 hEventObject[0] = WSACreateEvent();
553 hEventObject[1] = pThread->hThreadEvent;
555 handle = posix_fd2socket(fd);
556 CANT_HAPPEN(handle < 0);
559 if (flags & EMPTH_FD_READ)
560 events |= FD_READ | FD_ACCEPT | FD_CLOSE;
561 if (flags & EMPTH_FD_WRITE)
562 events |= FD_WRITE | FD_CLOSE;
563 WSAEventSelect(handle, hEventObject[0], events);
566 msec = timeout->tv_sec * 1000L + timeout->tv_usec / 1000L;
569 result = WSAWaitForMultipleEvents(2, hEventObject, FALSE, msec, FALSE);
572 case WSA_WAIT_TIMEOUT:
575 case WSA_WAIT_FAILED:
576 errno = WSAGetLastError();
583 WSAEventSelect(handle, hEventObject[0], 0);
585 WSACloseEvent(hEventObject[0]);
587 loc_RunThisThread(NULL);
591 /************************
594 * Wake up the specified thread.
597 empth_wakeup(empth_t *pThread)
599 loc_debug("waking up thread %s", pThread->szName);
601 /* Let it run if it is blocked... */
602 SetEvent(pThread->hThreadEvent);
605 /************************
608 * Put the given thread to sleep...
611 empth_sleep(time_t until)
613 long lSec = until - time(0) > 0 ? until - time(0) : 0;
614 empth_t *pThread = TlsGetValue(dwTLSIndex);
618 loc_BlockThisThread();
619 loc_debug("going to sleep %ld sec", lSec);
621 if (WaitForSingleObject(pThread->hThreadEvent, lSec * 1000L) !=
625 loc_debug("sleep done. Waiting to run.");
626 loc_RunThisThread(NULL);
627 } while (!iReturn && ((lSec = until - time(0)) > 0));
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);