2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2004, 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 the "LEGAL", "LICENSE", "CREDITS" and "README" files for all the
23 * related information and legal notices. It is expected that any future
24 * 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:
36 * EMPTHREADs for Windows NT.
38 * Actually, threads for any Win32 platform,
39 * like Win95, Win98, WinCE, and whatever other
40 * toy OSs are in our future from Microsoft.
42 * WIN32 has a full pre-emptive threading environment.
43 * But, Empire can not handle pre-emptive threading.
44 * Thus, we will use the threads, but limit the preemption
45 * using a Mutex semaphore.
50 #include <sys/types.h>
54 #include "empthread.h"
55 #include "prototypes.h"
57 #if defined(_WIN32) && defined(_EMPTH_WIN32)
62 #define loc_MIN_THREAD_STACK 16384
64 /************************
67 * The REAL empth_t thread structure.
68 * The external world only gets
69 * a void pointer to this.
71 typedef struct loc_Thread_t {
73 /* The thread name, passed in at create time. */
75 /* The thread description, 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 Event sem that the thread will wait/sleep on. */
98 /************************
101 * The REAL empth_sem_t structure.
102 * The external world only gets
103 * a void pointer to this.
105 typedef struct empth_sem_t {
109 /* An exclusion semaphore for this sem. */
111 /* An Event sem that the thread(s) will sleep on. */
114 /* The count variable */
119 /* This is the thread exclusion/non-premption mutex. */
120 /* The running thread has this MUTEX, and all others are */
121 /* either blocked on it, or waiting for some OS response. */
124 /* This is the thread startup event sem. */
125 /* We use this to lockstep when we are starting up threads. */
126 HANDLE hThreadStartEvent;
128 /* The Thread Local Storage index. We store the pThread pointer */
129 /* for each thread at this index. */
132 /* The current running thread. */
133 loc_Thread_t *pCurThread;
136 unsigned long ulTickAtStart;
138 /* Pointer out to global context. "player". */
139 /* From empth_init parameter. */
142 /* Global flags. From empth_init parameter. */
147 /************************
150 * Print out the current thread's status??
153 loc_debug(const char *pszFmt, ...)
156 unsigned long ulCurTick;
157 unsigned long ulRunTick;
158 unsigned long ulMs, ulSec, ulMin, ulHr;
159 loc_Thread_t *pThread =
160 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
163 if ((loc_GVAR.flags & EMPTH_PRINT) != 0) {
165 /* Ticks are in milliseconds */
166 ulCurTick = GetTickCount();
168 ulRunTick = ulCurTick - loc_GVAR.ulTickAtStart;
169 ulMs = ulRunTick % 1000L;
170 ulSec = (ulRunTick / 1000L) % 60L;
171 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
172 ulHr = (ulRunTick / (60L * 60L * 1000L));
174 va_start(vaList, pszFmt);
175 vsprintf(buf, pszFmt, vaList);
179 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
180 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
182 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
183 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
189 /************************
194 loc_FreeThreadInfo(loc_Thread_t *pThread)
197 if (pThread->hThreadEvent)
198 CloseHandle(pThread->hThreadEvent);
199 memset(pThread, 0, sizeof(*pThread));
204 /************************
207 * This thread wants to run.
208 * When this function returns, the
209 * globals are set to this thread info,
210 * and the thread owns the MUTEX sem.
215 loc_Thread_t *pThread =
216 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
218 if (pThread->bKilled) {
219 if (!pThread->bMainThread) {
220 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
221 loc_FreeThreadInfo(pThread);
226 /* Get the MUTEX semaphore, wait forever. */
227 WaitForSingleObject(loc_GVAR.hThreadMutex, INFINITE);
229 if (!loc_GVAR.pCurThread) {
230 /* Set the globals to this thread. */
231 *loc_GVAR.ppvUserData = pThread->pvUserData;
233 loc_GVAR.pCurThread = pThread;
235 /* Hmm, a problem, eh? */
236 logerror("RunThisThread, someone already running.");
240 /************************
241 * loc_BlockThisThread
243 * This thread was running. It no longer wants to.
246 loc_BlockThisThread()
248 loc_Thread_t *pThread =
249 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
251 if (loc_GVAR.pCurThread == pThread) {
252 /* Reset the globals back to original */
254 loc_GVAR.pCurThread = NULL;
255 *loc_GVAR.ppvUserData = NULL;
257 /* Release the MUTEX */
258 ReleaseMutex(loc_GVAR.hThreadMutex);
260 /* Hmm, this thread was not the running one. */
261 logerror("BlockThisThread, not running.");
266 /************************
267 * loc_SleepThisThread
270 loc_SleepThisThread(unsigned long ulMillisecs)
272 loc_Thread_t *pThread =
273 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
275 /* Make sure the event thread is clean. */
276 ResetEvent(pThread->hThreadEvent);
278 /* Get the MUTEX semaphore, wait the number of MS */
279 WaitForSingleObject(pThread->hThreadEvent, ulMillisecs);
283 /************************
286 * This is the main line of each thread.
287 * This is really a static local func....
290 empth_threadMain(void *pvData)
294 loc_Thread_t *pThread = (loc_Thread_t *)pvData;
300 /* Store pThread on this thread. */
301 TlsSetValue(loc_GVAR.dwTLSIndex, pvData);
303 /* Get the ID of the thread. */
304 pThread->ulThreadID = GetCurrentThreadId();
306 /* Signal that the thread has started. */
307 SetEvent(loc_GVAR.hThreadStartEvent);
309 /* seed the rand() function */
311 srand(now ^ (unsigned int)pThread);
313 /* Switch to this thread context */
316 /* Run the thread. */
317 if (pThread->pfnEntry)
318 pThread->pfnEntry(pThread->pvUserData);
320 /* Kill the thread. */
324 /************************
327 * Initialize the thread environment.
329 * This is called from the program
333 empth_init(char **ctx_ptr, int flags)
335 loc_Thread_t *pThread = NULL;
337 loc_GVAR.ulTickAtStart = GetTickCount();
338 loc_GVAR.ppvUserData = ctx_ptr;
339 loc_GVAR.flags = flags;
340 loc_GVAR.dwTLSIndex = TlsAlloc();
342 /* Create the thread mutex sem. */
343 /* Initally unowned. */
344 loc_GVAR.hThreadMutex = CreateMutex(NULL, FALSE, NULL);
345 if (!loc_GVAR.hThreadMutex) {
346 logerror("Failed to create mutex");
350 /* Create the thread start event sem. */
351 /* Automatic state reset. */
352 loc_GVAR.hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
353 if (!loc_GVAR.hThreadStartEvent) {
354 logerror("Failed to create mutex");
358 /* Create the global Thread context. */
359 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
361 logerror("not enough memory to create main thread.");
364 memset(pThread, 0, sizeof(*pThread));
366 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
367 strncpy(pThread->szDesc, "The main process",
368 sizeof(pThread->szDesc) - 1);
369 pThread->ulThreadID = GetCurrentThreadId();
370 pThread->bMainThread = TRUE;
372 TlsSetValue(loc_GVAR.dwTLSIndex, pThread);
374 /* Make this the running thread. */
377 logerror("NT pthreads initialized");
382 /************************
385 * Create a new thread.
387 * prio - priority, not particularly useful in our context.
388 * entry - entry point function for thread.
390 * flags - debug control.
391 * LWP_STACKCHECK - not needed
392 * name - name of the thread, for debug.
393 * desc - description of thread, for debug.
394 * ud - "user data". The "ctx_ptr" gets this value
395 * when the thread is active.
396 * It is also passed to the entry function...
399 empth_create(int prio, void (*entry)(void *), int size, int flags,
400 char *name, char *desc, void *ud)
402 loc_Thread_t *pThread = NULL;
404 loc_debug("creating new thread %s:%s", name, desc);
406 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
408 logerror("not enough memory to create thread: %s (%s)", name,
412 memset(pThread, 0, sizeof(*pThread));
414 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
415 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
416 pThread->pvUserData = ud;
417 pThread->pfnEntry = entry;
418 pThread->bMainThread = FALSE;
420 /* Create thread event sem, auto reset. */
421 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
423 if (size < loc_MIN_THREAD_STACK)
424 size = loc_MIN_THREAD_STACK;
426 pThread->ulThreadID = _beginthread(empth_threadMain, size,
428 if (pThread->ulThreadID == -1) {
429 logerror("can not create thread: %s (%s): %s", name, desc,
434 loc_debug("new thread id is %ld", pThread->ulThreadID);
439 loc_FreeThreadInfo(pThread);
445 /************************
451 loc_Thread_t *pThread =
452 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
457 /************************
463 loc_Thread_t *pThread =
464 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
466 loc_BlockThisThread();
468 loc_debug("empth_exit");
470 if (pThread->bMainThread) {
472 /* The main line. Wait forever. */
474 printf("\nEmpire Server>");
475 fgets(buf, sizeof(buf), stdin);
476 if (!strnicmp(buf, "quit", 4))
480 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
481 loc_FreeThreadInfo(pThread);
486 /************************
489 * Yield processing to another thread.
494 loc_BlockThisThread();
498 /************************
501 * Kill off the thread.
504 empth_terminate(empth_t *a)
506 loc_Thread_t *pThread = (loc_Thread_t *)a;
508 loc_debug("killing thread %s", pThread->szName);
509 pThread->bKilled = TRUE;
511 SetEvent(pThread->hThreadEvent);
514 /************************
517 * Do a select on the given file.
520 * This would be one of the main functions used within
524 empth_select(int fd, int flags)
526 loc_Thread_t *pThread =
527 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
530 struct lwpProc *proc;
534 loc_debug("%s select on %d",
535 flags == EMPTH_FD_READ ? "read" : "write", fd);
536 loc_BlockThisThread();
547 FD_SET(fd, &readmask);
550 FD_SET(fd, &writemask);
553 logerror("bad flag %d passed to empth_select", flags);
557 n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
560 if (errno == EINTR) {
561 /* go handle the signal */
562 loc_debug("select broken by signal");
566 /* strange but we dont get EINTR on select broken by signal */
567 loc_debug("select failed (%s)", strerror(errno));
572 if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
573 loc_debug("input ready");
576 if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
577 loc_debug("output ready");
586 /************************
592 loc_Thread_t *pThread =
593 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
595 loc_debug("got alarm signal %d", sig);
597 /* Let it run if it is blocked like... */
598 SetEvent(pThread->hThreadEvent);
601 /************************
604 * Wake up the specified thread.
607 empth_wakeup(empth_t *a)
609 loc_Thread_t *pThread = (loc_Thread_t *)a;
611 loc_debug("waking up thread %s", pThread->szName);
613 /* Let it run if it is blocked... */
614 SetEvent(pThread->hThreadEvent);
617 /************************
620 * Put the given thread to sleep...
623 empth_sleep(long until)
625 loc_Thread_t *pThread =
626 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
629 ulSec = until - time(0);
631 loc_debug("going to sleep %ld sec", ulSec);
633 loc_BlockThisThread();
635 WaitForSingleObject(pThread->hThreadEvent, (ulSec * 1000));
637 loc_debug("sleep done. Waiting to run.");
643 /************************
646 * Create a signalling semaphore.
649 empth_sem_create(char *name, int cnt)
653 pSem = (loc_Sem_t *)malloc(sizeof(*pSem));
655 logerror("out of memory at %s:%d", __FILE__, __LINE__);
659 memset(pSem, 0, sizeof(pSem));
660 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
662 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
663 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
669 /************************
672 * Hit/signal the specified semaphore.
675 empth_sem_signal(empth_sem_t *sm)
677 loc_Sem_t *pSem = (loc_Sem_t *)sm;
679 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
681 /* Wait for the Semaphore */
682 WaitForSingleObject(pSem->hMutex, INFINITE);
684 if (pSem->count++ < 0) {
685 SetEvent(pSem->hEvent);
688 ReleaseMutex(pSem->hMutex);
691 /************************
694 * Wait for the specified signal semaphore
698 empth_sem_wait(empth_sem_t *sm)
700 loc_Thread_t *pThread =
701 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
702 loc_Sem_t *pSem = (loc_Sem_t *)sm;
704 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
706 /* Remove the thread from the running state. */
707 loc_BlockThisThread();
709 /* Wait for the Semaphore */
710 WaitForSingleObject(pSem->hMutex, INFINITE);
711 if (--pSem->count < 0) {
712 loc_debug("blocking");
713 ReleaseMutex(pSem->hMutex);
715 WaitForSingleObject(pSem->hEvent, INFINITE);
717 loc_debug("waking up");
719 ReleaseMutex(pSem->hMutex);