2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2000, 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.
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.
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)
292 loc_Thread_t *pThread = (loc_Thread_t *)pvData;
298 /* Store pThread on this thread. */
299 TlsSetValue(loc_GVAR.dwTLSIndex, pvData);
301 /* Get the ID of the thread. */
302 pThread->ulThreadID = GetCurrentThreadId();
304 /* Signal that the thread has started. */
305 SetEvent(loc_GVAR.hThreadStartEvent);
307 /* Switch to this thread context */
310 /* Run the thread. */
311 if (pThread->pfnEntry)
312 pThread->pfnEntry(pThread->pvUserData);
314 /* Kill the thread. */
318 /************************
321 * Initialize the thread environment.
323 * This is called from the program
327 empth_init(char **ctx_ptr, int flags)
329 loc_Thread_t *pThread = NULL;
331 loc_GVAR.ulTickAtStart = GetTickCount();
332 loc_GVAR.ppvUserData = ctx_ptr;
333 loc_GVAR.flags = flags;
334 loc_GVAR.dwTLSIndex = TlsAlloc();
336 /* Create the thread mutex sem. */
337 /* Initally unowned. */
338 loc_GVAR.hThreadMutex = CreateMutex(NULL, FALSE, NULL);
339 if (!loc_GVAR.hThreadMutex) {
340 logerror("Failed to create mutex");
344 /* Create the thread start event sem. */
345 /* Automatic state reset. */
346 loc_GVAR.hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
347 if (!loc_GVAR.hThreadStartEvent) {
348 logerror("Failed to create mutex");
352 /* Create the global Thread context. */
353 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
355 logerror("not enough memory to create main thread.");
358 memset(pThread, 0, sizeof(*pThread));
360 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
361 strncpy(pThread->szDesc, "The main process",
362 sizeof(pThread->szDesc) - 1);
363 pThread->ulThreadID = GetCurrentThreadId();
364 pThread->bMainThread = TRUE;
366 TlsSetValue(loc_GVAR.dwTLSIndex, pThread);
368 /* Make this the running thread. */
371 logerror("NT pthreads initialized");
376 /************************
379 * Create a new thread.
381 * prio - priority, not particularly useful in our context.
382 * entry - entry point function for thread.
384 * flags - debug control.
385 * LWP_STACKCHECK - not needed
386 * name - name of the thread, for debug.
387 * desc - description of thread, for debug.
388 * ud - "user data". The "ctx_ptr" gets this value
389 * when the thread is active.
390 * It is also passed to the entry function...
393 empth_create(int prio, void (*entry) (), int size, int flags,
394 char *name, char *desc, void *ud)
396 loc_Thread_t *pThread = NULL;
398 loc_debug("creating new thread %s:%s", name, desc);
400 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
402 logerror("not enough memory to create thread: %s (%s)", name,
406 memset(pThread, 0, sizeof(*pThread));
408 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
409 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
410 pThread->pvUserData = ud;
411 pThread->pfnEntry = entry;
412 pThread->bMainThread = FALSE;
414 /* Create thread event sem, auto reset. */
415 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
417 if (size < loc_MIN_THREAD_STACK)
418 size = loc_MIN_THREAD_STACK;
420 pThread->ulThreadID = _beginthread(empth_threadMain, size,
422 if (pThread->ulThreadID == -1) {
423 logerror("can not create thread: %s (%s): %s", name, desc,
428 loc_debug("new thread id is %ld", pThread->ulThreadID);
433 loc_FreeThreadInfo(pThread);
439 /************************
445 loc_Thread_t *pThread =
446 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
451 /************************
457 s_char *getlogfile();
459 loc_Thread_t *pThread =
460 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
462 loc_BlockThisThread();
464 loc_debug("empth_exit");
466 if (pThread->bMainThread) {
468 /* The main line. Wait forever. */
469 if (getlogfile() == (s_char *)0)
471 printf("log file: %s\n", getlogfile());
473 printf("\nEmpire Server>");
474 fgets(buf, sizeof(buf), stdin);
475 if (!strnicmp(buf, "quit", 4))
478 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
479 loc_FreeThreadInfo(pThread);
481 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
482 loc_FreeThreadInfo(pThread);
487 /************************
490 * Yield processing to another thread.
495 loc_BlockThisThread();
499 /************************
502 * Kill off the thread.
505 empth_terminate(empth_t *a)
507 loc_Thread_t *pThread = (loc_Thread_t *)a;
509 loc_debug("killing thread %s", pThread->szName);
510 pThread->bKilled = TRUE;
512 SetEvent(pThread->hThreadEvent);
515 /************************
518 * Do a select on the given file.
521 * This would be one of the main functions used within
525 empth_select(int fd, int flags)
527 loc_Thread_t *pThread =
528 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
531 struct lwpProc *proc;
535 loc_debug("%s select on %d",
536 flags == EMPTH_FD_READ ? "read" : "write", fd);
537 loc_BlockThisThread();
548 FD_SET(fd, &readmask);
551 FD_SET(fd, &writemask);
554 logerror("bad flag %d passed to empth_select", flags);
558 n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
561 if (errno == EINTR) {
562 /* go handle the signal */
563 loc_debug("select broken by signal");
567 /* strange but we dont get EINTR on select broken by signal */
568 loc_debug("select failed (%s)", strerror(errno));
573 if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
574 loc_debug("input ready");
577 if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
578 loc_debug("output ready");
587 /************************
593 loc_Thread_t *pThread =
594 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
596 loc_debug("got alarm signal %d", sig);
598 /* Let it run if it is blocked like... */
599 SetEvent(pThread->hThreadEvent);
602 /************************
605 * Wake up the specified thread.
608 empth_wakeup(empth_t *a)
610 loc_Thread_t *pThread = (loc_Thread_t *)a;
612 loc_debug("waking up thread %s", pThread->szName);
614 /* Let it run if it is blocked... */
615 SetEvent(pThread->hThreadEvent);
618 /************************
621 * Put the given thread to sleep...
624 empth_sleep(long until)
626 loc_Thread_t *pThread =
627 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
630 ulSec = until - time(0);
632 loc_debug("going to sleep %ld sec", ulSec);
634 loc_BlockThisThread();
636 WaitForSingleObject(pThread->hThreadEvent, (ulSec * 1000));
638 loc_debug("sleep done. Waiting to run.");
644 /************************
647 * Create a signalling semaphore.
650 empth_sem_create(char *name, int cnt)
654 pSem = (loc_Sem_t *)malloc(sizeof(*pSem));
656 logerror("out of memory at %s:%d", __FILE__, __LINE__);
660 memset(pSem, 0, sizeof(pSem));
661 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
663 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
664 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
670 /************************
673 * Hit/signal the specified semaphore.
676 empth_sem_signal(empth_sem_t *sm)
678 loc_Sem_t *pSem = (loc_Sem_t *)sm;
680 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
682 /* Wait for the Semaphore */
683 WaitForSingleObject(pSem->hMutex, INFINITE);
685 if (pSem->count++ < 0) {
686 SetEvent(pSem->hEvent);
689 ReleaseMutex(pSem->hMutex);
692 /************************
695 * Wait for the specified signal semaphore
699 empth_sem_wait(empth_sem_t *sm)
701 loc_Thread_t *pThread =
702 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
703 loc_Sem_t *pSem = (loc_Sem_t *)sm;
705 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
707 /* Remove the thread from the running state. */
708 loc_BlockThisThread();
710 /* Wait for the Semaphore */
711 WaitForSingleObject(pSem->hMutex, INFINITE);
712 if (--pSem->count < 0) {
713 loc_debug("blocking");
714 ReleaseMutex(pSem->hMutex);
716 WaitForSingleObject(pSem->hEvent, INFINITE);
718 loc_debug("waking up");
720 ReleaseMutex(pSem->hMutex);