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)
63 #define loc_MIN_THREAD_STACK 16384
65 /************************
68 * The REAL empth_t thread structure.
69 * The external world only gets
70 * a void pointer to this.
72 typedef struct loc_Thread_t {
74 /* The thread name, passed in at create time. */
76 /* The thread description, passed in at create time. */
79 /* True if this is the main line, and not a real thread. */
82 /* The user data passed in at create time. */
85 /* True if this thread has been killed. */
88 /* The entry function for the thread. */
89 void (*pfnEntry) (void *);
91 /* The system thread ID. */
92 unsigned long ulThreadID;
94 /* An Event sem that the thread will wait/sleep on. */
99 /************************
102 * The REAL empth_sem_t structure.
103 * The external world only gets
104 * a void pointer to this.
106 typedef struct empth_sem_t {
110 /* An exclusion semaphore for this sem. */
112 /* An Event sem that the thread(s) will sleep on. */
115 /* The count variable */
120 /* This is the thread exclusion/non-premption mutex. */
121 /* The running thread has this MUTEX, and all others are */
122 /* either blocked on it, or waiting for some OS response. */
125 /* This is the thread startup event sem. */
126 /* We use this to lockstep when we are starting up threads. */
127 HANDLE hThreadStartEvent;
129 /* The Thread Local Storage index. We store the pThread pointer */
130 /* for each thread at this index. */
133 /* The current running thread. */
134 loc_Thread_t *pCurThread;
137 unsigned long ulTickAtStart;
139 /* Pointer out to global context. "player". */
140 /* From empth_init parameter. */
143 /* Global flags. From empth_init parameter. */
148 /************************
151 * Print out the current thread's status??
154 loc_debug(const char *pszFmt, ...)
157 unsigned long ulCurTick;
158 unsigned long ulRunTick;
159 unsigned long ulMs, ulSec, ulMin, ulHr;
160 loc_Thread_t *pThread =
161 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
164 if ((loc_GVAR.flags & EMPTH_PRINT) != 0) {
166 /* Ticks are in milliseconds */
167 ulCurTick = GetTickCount();
169 ulRunTick = ulCurTick - loc_GVAR.ulTickAtStart;
170 ulMs = ulRunTick % 1000L;
171 ulSec = (ulRunTick / 1000L) % 60L;
172 ulMin = (ulRunTick / (60L * 1000L)) % 60L;
173 ulHr = (ulRunTick / (60L * 60L * 1000L));
175 va_start(vaList, pszFmt);
176 vsprintf(buf, pszFmt, vaList);
180 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
181 ulHr, ulMin, ulSec, ulMs, pThread->szName, buf);
183 printf("%ld:%02ld:%02ld.%03ld %17s: %s\n",
184 ulHr, ulMin, ulSec, ulMs, "UNKNOWN", buf);
190 /************************
195 loc_FreeThreadInfo(loc_Thread_t *pThread)
198 if (pThread->hThreadEvent)
199 CloseHandle(pThread->hThreadEvent);
200 memset(pThread, 0, sizeof(*pThread));
205 /************************
208 * This thread wants to run.
209 * When this function returns, the
210 * globals are set to this thread info,
211 * and the thread owns the MUTEX sem.
216 loc_Thread_t *pThread =
217 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
219 if (pThread->bKilled) {
220 if (!pThread->bMainThread) {
221 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
222 loc_FreeThreadInfo(pThread);
227 /* Get the MUTEX semaphore, wait forever. */
228 WaitForSingleObject(loc_GVAR.hThreadMutex, INFINITE);
230 if (!loc_GVAR.pCurThread) {
231 /* Set the globals to this thread. */
232 *loc_GVAR.ppvUserData = pThread->pvUserData;
234 loc_GVAR.pCurThread = pThread;
236 /* Hmm, a problem, eh? */
237 logerror("RunThisThread, someone already running.");
241 /************************
242 * loc_BlockThisThread
244 * This thread was running. It no longer wants to.
247 loc_BlockThisThread()
249 loc_Thread_t *pThread =
250 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
252 if (loc_GVAR.pCurThread == pThread) {
253 /* Reset the globals back to original */
255 loc_GVAR.pCurThread = NULL;
256 *loc_GVAR.ppvUserData = NULL;
258 /* Release the MUTEX */
259 ReleaseMutex(loc_GVAR.hThreadMutex);
261 /* Hmm, this thread was not the running one. */
262 logerror("BlockThisThread, not running.");
267 /************************
268 * loc_SleepThisThread
271 loc_SleepThisThread(unsigned long ulMillisecs)
273 loc_Thread_t *pThread =
274 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
276 /* Make sure the event thread is clean. */
277 ResetEvent(pThread->hThreadEvent);
279 /* Get the MUTEX semaphore, wait the number of MS */
280 WaitForSingleObject(pThread->hThreadEvent, ulMillisecs);
284 /************************
287 * This is the main line of each thread.
288 * This is really a static local func....
291 empth_threadMain(void *pvData)
295 loc_Thread_t *pThread = (loc_Thread_t *)pvData;
301 /* Store pThread on this thread. */
302 TlsSetValue(loc_GVAR.dwTLSIndex, pvData);
304 /* Get the ID of the thread. */
305 pThread->ulThreadID = GetCurrentThreadId();
307 /* Signal that the thread has started. */
308 SetEvent(loc_GVAR.hThreadStartEvent);
310 /* seed the rand() function */
312 srand(now ^ (unsigned int)pThread);
314 /* Switch to this thread context */
317 /* Run the thread. */
318 if (pThread->pfnEntry)
319 pThread->pfnEntry(pThread->pvUserData);
321 /* Kill the thread. */
325 /************************
328 * Initialize the thread environment.
330 * This is called from the program
334 empth_init(char **ctx_ptr, int flags)
336 loc_Thread_t *pThread = NULL;
338 loc_GVAR.ulTickAtStart = GetTickCount();
339 loc_GVAR.ppvUserData = ctx_ptr;
340 loc_GVAR.flags = flags;
341 loc_GVAR.dwTLSIndex = TlsAlloc();
343 /* Create the thread mutex sem. */
344 /* Initally unowned. */
345 loc_GVAR.hThreadMutex = CreateMutex(NULL, FALSE, NULL);
346 if (!loc_GVAR.hThreadMutex) {
347 logerror("Failed to create mutex");
351 /* Create the thread start event sem. */
352 /* Automatic state reset. */
353 loc_GVAR.hThreadStartEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
354 if (!loc_GVAR.hThreadStartEvent) {
355 logerror("Failed to create mutex");
359 /* Create the global Thread context. */
360 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
362 logerror("not enough memory to create main thread.");
365 memset(pThread, 0, sizeof(*pThread));
367 strncpy(pThread->szName, "Main", sizeof(pThread->szName) - 1);
368 strncpy(pThread->szDesc, "The main process",
369 sizeof(pThread->szDesc) - 1);
370 pThread->ulThreadID = GetCurrentThreadId();
371 pThread->bMainThread = TRUE;
373 TlsSetValue(loc_GVAR.dwTLSIndex, pThread);
375 /* Make this the running thread. */
378 logerror("NT pthreads initialized");
383 /************************
386 * Create a new thread.
388 * prio - priority, not particularly useful in our context.
389 * entry - entry point function for thread.
391 * flags - debug control.
392 * LWP_STACKCHECK - not needed
393 * name - name of the thread, for debug.
394 * desc - description of thread, for debug.
395 * ud - "user data". The "ctx_ptr" gets this value
396 * when the thread is active.
397 * It is also passed to the entry function...
400 empth_create(int prio, void (*entry)(void *), int size, int flags,
401 char *name, char *desc, void *ud)
403 loc_Thread_t *pThread = NULL;
405 loc_debug("creating new thread %s:%s", name, desc);
407 pThread = (loc_Thread_t *)malloc(sizeof(*pThread));
409 logerror("not enough memory to create thread: %s (%s)", name,
413 memset(pThread, 0, sizeof(*pThread));
415 strncpy(pThread->szName, name, sizeof(pThread->szName) - 1);
416 strncpy(pThread->szDesc, desc, sizeof(pThread->szDesc) - 1);
417 pThread->pvUserData = ud;
418 pThread->pfnEntry = entry;
419 pThread->bMainThread = FALSE;
421 /* Create thread event sem, auto reset. */
422 pThread->hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
424 if (size < loc_MIN_THREAD_STACK)
425 size = loc_MIN_THREAD_STACK;
427 pThread->ulThreadID = _beginthread(empth_threadMain, size,
429 if (pThread->ulThreadID == -1) {
430 logerror("can not create thread: %s (%s): %s", name, desc,
435 loc_debug("new thread id is %ld", pThread->ulThreadID);
440 loc_FreeThreadInfo(pThread);
446 /************************
452 loc_Thread_t *pThread =
453 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
458 /************************
464 loc_Thread_t *pThread =
465 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
467 loc_BlockThisThread();
469 loc_debug("empth_exit");
471 if (pThread->bMainThread) {
472 /* The main line. Wait forever. */
475 if (service_stopped())
480 printf("\nEmpire Server>");
481 fgets(buf, sizeof(buf), stdin);
482 if (!strnicmp(buf, "quit", 4))
487 TlsSetValue(loc_GVAR.dwTLSIndex, NULL);
488 loc_FreeThreadInfo(pThread);
493 /************************
496 * Yield processing to another thread.
501 loc_BlockThisThread();
505 /************************
508 * Kill off the thread.
511 empth_terminate(empth_t *a)
513 loc_Thread_t *pThread = (loc_Thread_t *)a;
515 loc_debug("killing thread %s", pThread->szName);
516 pThread->bKilled = TRUE;
518 SetEvent(pThread->hThreadEvent);
521 /************************
524 * Do a select on the given file.
527 * This would be one of the main functions used within
531 empth_select(int fd, int flags)
533 loc_Thread_t *pThread =
534 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
537 struct lwpProc *proc;
541 loc_debug("%s select on %d",
542 flags == EMPTH_FD_READ ? "read" : "write", fd);
543 loc_BlockThisThread();
554 FD_SET(fd, &readmask);
557 FD_SET(fd, &writemask);
560 logerror("bad flag %d passed to empth_select", flags);
564 n = select(fd + 1, &readmask, &writemask, (fd_set *) 0, &tv);
567 if (errno == EINTR) {
568 /* go handle the signal */
569 loc_debug("select broken by signal");
573 /* strange but we dont get EINTR on select broken by signal */
574 loc_debug("select failed (%s)", strerror(errno));
579 if (flags == EMPTH_FD_READ && FD_ISSET(fd, &readmask)) {
580 loc_debug("input ready");
583 if (flags == EMPTH_FD_WRITE && FD_ISSET(fd, &writemask)) {
584 loc_debug("output ready");
593 /************************
599 loc_Thread_t *pThread =
600 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
602 loc_debug("got alarm signal %d", sig);
604 /* Let it run if it is blocked like... */
605 SetEvent(pThread->hThreadEvent);
608 /************************
611 * Wake up the specified thread.
614 empth_wakeup(empth_t *a)
616 loc_Thread_t *pThread = (loc_Thread_t *)a;
618 loc_debug("waking up thread %s", pThread->szName);
620 /* Let it run if it is blocked... */
621 SetEvent(pThread->hThreadEvent);
624 /************************
627 * Put the given thread to sleep...
630 empth_sleep(long until)
632 loc_Thread_t *pThread =
633 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
636 ulSec = until - time(0);
638 loc_debug("going to sleep %ld sec", ulSec);
640 loc_BlockThisThread();
642 WaitForSingleObject(pThread->hThreadEvent, (ulSec * 1000));
644 loc_debug("sleep done. Waiting to run.");
650 /************************
653 * Create a signalling semaphore.
656 empth_sem_create(char *name, int cnt)
660 pSem = (loc_Sem_t *)malloc(sizeof(*pSem));
662 logerror("out of memory at %s:%d", __FILE__, __LINE__);
666 memset(pSem, 0, sizeof(pSem));
667 strncpy(pSem->szName, name, sizeof(pSem->szName) - 1);
669 pSem->hMutex = CreateMutex(NULL, FALSE, NULL);
670 pSem->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
676 /************************
679 * Hit/signal the specified semaphore.
682 empth_sem_signal(empth_sem_t *sm)
684 loc_Sem_t *pSem = (loc_Sem_t *)sm;
686 loc_debug("signal on semaphore %s:%d", pSem->szName, pSem->count);
688 /* Wait for the Semaphore */
689 WaitForSingleObject(pSem->hMutex, INFINITE);
691 if (pSem->count++ < 0) {
692 SetEvent(pSem->hEvent);
695 ReleaseMutex(pSem->hMutex);
698 /************************
701 * Wait for the specified signal semaphore
705 empth_sem_wait(empth_sem_t *sm)
707 loc_Thread_t *pThread =
708 (loc_Thread_t *)TlsGetValue(loc_GVAR.dwTLSIndex);
709 loc_Sem_t *pSem = (loc_Sem_t *)sm;
711 loc_debug("wait on semaphore %s:%d", pSem->szName, pSem->count);
713 /* Remove the thread from the running state. */
714 loc_BlockThisThread();
716 /* Wait for the Semaphore */
717 WaitForSingleObject(pSem->hMutex, INFINITE);
718 if (--pSem->count < 0) {
719 loc_debug("blocking");
720 ReleaseMutex(pSem->hMutex);
722 WaitForSingleObject(pSem->hEvent, INFINITE);
724 loc_debug("waking up");
726 ReleaseMutex(pSem->hMutex);