summaryrefslogtreecommitdiff
path: root/src/libs/threads/thrcommon.c
blob: bc5475137d4b449c0775d39e2879b90e48bb3995 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include "libs/threadlib.h"
#include "libs/timelib.h"
#include "libs/log.h"
#include "libs/async.h"
#include "libs/memlib.h"
#include "thrcommon.h"

#define LIFECYCLE_SIZE 8
typedef struct {
	ThreadFunction func;
	void *data;
	SDWORD stackSize;
	Semaphore sem;
	Thread value;
#ifdef NAMED_SYNCHRO
	const char *name;
#endif
} SpawnRequest_struct;

typedef SpawnRequest_struct *SpawnRequest;

static Mutex        lifecycleMutex;
static SpawnRequest pendingBirth[LIFECYCLE_SIZE];
static Thread       pendingDeath[LIFECYCLE_SIZE];

void
InitThreadSystem (void)
{
	int i;
	NativeInitThreadSystem ();
	for (i = 0; i < LIFECYCLE_SIZE; i++)
	{
		pendingBirth[i] = NULL;
		pendingDeath[i] = NULL;
	}
	lifecycleMutex = CreateMutex ("Thread Lifecycle Mutex", SYNC_CLASS_RESOURCE);
}

void
UnInitThreadSystem (void)
{
	NativeUnInitThreadSystem ();
	DestroyMutex (lifecycleMutex);
}

static Thread
FlagStartThread (SpawnRequest s)
{
	int i;
	LockMutex (lifecycleMutex);
	for (i = 0; i < LIFECYCLE_SIZE; i++)
	{
		if (pendingBirth[i] == NULL)
		{
			pendingBirth[i] = s;
			UnlockMutex (lifecycleMutex);
			if (s->sem)
			{
				Thread result;
				SetSemaphore (s->sem);
				DestroySemaphore (s->sem);
				result = s->value;
				HFree (s);
				return result;
			}
			return NULL;
		}
	}
	log_add (log_Fatal, "Thread Lifecycle array filled.  This is a fatal error!  Make LIFECYCLE_SIZE something larger than %d.", LIFECYCLE_SIZE);
	exit (EXIT_FAILURE);
}

void
FinishThread (Thread thread)
{
	int i;
	LockMutex (lifecycleMutex);
	for (i = 0; i < LIFECYCLE_SIZE; i++)
	{
		if (pendingDeath[i] == NULL)
		{
			pendingDeath[i] = thread;
			UnlockMutex (lifecycleMutex);
			return;
		}
	}
	log_add (log_Fatal, "Thread Lifecycle array filled.  This is a fatal error!  Make LIFECYCLE_SIZE something larger than %d.", LIFECYCLE_SIZE);
	exit (EXIT_FAILURE);
}

/* Only call from main thread! */
void
ProcessThreadLifecycles (void)
{
	int i;
	LockMutex (lifecycleMutex);
	for (i = 0; i < LIFECYCLE_SIZE; i++)
	{
		SpawnRequest s = pendingBirth[i];
		if (s != NULL)
		{
#ifdef NAMED_SYNCHRO
			s->value = NativeCreateThread (s->func, s->data, s->stackSize, s->name);
#else
			s->value = NativeCreateThread (s->func, s->data, s->stackSize);
#endif
			if (s->sem)
			{
				ClearSemaphore (s->sem);
				/* The spawning thread's FlagStartThread will clean up s */
			}
			else
			{
				/* The thread value has been lost to the game logic.  We must
				   clean up s ourself. */
				HFree (s);
			}
			pendingBirth[i] = NULL;
		}
	}

	for (i = 0; i < LIFECYCLE_SIZE; i++)
	{
		Thread t = pendingDeath[i];
		if (t != NULL)
		{
			WaitThread (t, NULL);
			pendingDeath[i] = NULL;	
			DestroyThread (t);
		}
	}
	UnlockMutex (lifecycleMutex);
}


/* The Create routines look different based on whether NAMED_SYNCHRO
   is defined or not. */

#ifdef NAMED_SYNCHRO
Thread
CreateThread_Core (ThreadFunction func, void *data, SDWORD stackSize, const char *name)
{
	SpawnRequest s = HMalloc(sizeof (SpawnRequest_struct));
	s->func = func;
	s->data = data;
	s->stackSize = stackSize;
	s->name = name;
	s->sem = CreateSemaphore (0, "SpawnRequest semaphore", SYNC_CLASS_RESOURCE);
	return FlagStartThread (s);
}

void
StartThread_Core (ThreadFunction func, void *data, SDWORD stackSize, const char *name)
{
	SpawnRequest s = HMalloc(sizeof (SpawnRequest_struct));
	s->func = func;
	s->data = data;
	s->stackSize = stackSize;
	s->name = name;
	s->sem = NULL;
	FlagStartThread (s);
}

Mutex
CreateMutex_Core (const char *name, DWORD syncClass)
{
	return NativeCreateMutex (name, syncClass);
}

Semaphore
CreateSemaphore_Core (DWORD initial, const char *name, DWORD syncClass)
{
	return NativeCreateSemaphore (initial, name, syncClass);
}

RecursiveMutex
CreateRecursiveMutex_Core (const char *name, DWORD syncClass)
{
	return NativeCreateRecursiveMutex (name, syncClass);
}

CondVar
CreateCondVar_Core (const char *name, DWORD syncClass)
{
	return NativeCreateCondVar (name, syncClass);
}

#else
/* These are the versions of Create* without the names. */
Thread
CreateThread_Core (ThreadFunction func, void *data, SDWORD stackSize)
{
	SpawnRequest s = HMalloc(sizeof (SpawnRequest_struct));
	s->func = func;
	s->data = data;
	s->stackSize = stackSize;
	s->sem = CreateSemaphore (0, "SpawnRequest semaphore", SYNC_CLASS_RESOURCE);
	return FlagStartThread (s);
}

void
StartThread_Core (ThreadFunction func, void *data, SDWORD stackSize)
{
	SpawnRequest s = HMalloc(sizeof (SpawnRequest_struct));
	s->func = func;
	s->data = data;
	s->stackSize = stackSize;
	s->sem = NULL;
	FlagStartThread (s);
}

Mutex
CreateMutex_Core (void)
{
	return NativeCreateMutex ();
}

Semaphore
CreateSemaphore_Core (DWORD initial)
{
	return NativeCreateSemaphore (initial);
}

RecursiveMutex
CreateRecursiveMutex_Core (void)
{
	return NativeCreateRecursiveMutex ();
}

CondVar
CreateCondVar_Core (void)
{
	return NativeCreateCondVar ();
}
#endif

void
DestroyThread (Thread t)
{
	NativeDestroyThread (t);
}

ThreadLocal *
CreateThreadLocal (void)
{
	ThreadLocal *tl = HMalloc (sizeof (ThreadLocal));
	tl->flushSem = CreateSemaphore (0, "FlushGraphics", SYNC_CLASS_VIDEO);
	return tl;
}

void
DestroyThreadLocal (ThreadLocal *tl)
{
	DestroySemaphore (tl->flushSem);
	HFree (tl);
}

ThreadLocal *
GetMyThreadLocal (void)
{
	return NativeGetMyThreadLocal ();
}

void
WaitThread (Thread thread, int *status)
{
	NativeWaitThread (thread, status);
}

#ifdef DEBUG_SLEEP
extern uint32 mainThreadId;
extern uint32 SDL_ThreadID(void);
#endif  /* DEBUG_SLEEP */

void
HibernateThread (TimePeriod timePeriod)
{
#ifdef DEBUG_SLEEP
	if (SDL_ThreadID() == mainThreadId)
		log_add (log_Debug, "HibernateThread called from main thread.\n");
#endif  /* DEBUG_SLEEP */

	NativeSleepThread (timePeriod);
}

void
HibernateThreadUntil (TimeCount wakeTime)
{
#ifdef DEBUG_SLEEP
	if (SDL_ThreadID() == mainThreadId)
		log_add (log_Debug, "HibernateThreadUntil called from main "
				"thread.\n");
#endif  /* DEBUG_SLEEP */

	NativeSleepThreadUntil (wakeTime);
}

void
SleepThread (TimePeriod timePeriod)
{
	TimeCount now;

#ifdef DEBUG_SLEEP
	if (SDL_ThreadID() != mainThreadId)
		log_add (log_Debug, "SleepThread called from non-main "
				"thread.\n");
#endif  /* DEBUG_SLEEP */

	now = GetTimeCounter ();
	SleepThreadUntil (now + timePeriod);
}

// Sleep until wakeTime, but call asynchrounous operations until then.
void
SleepThreadUntil (TimeCount wakeTime)
{
#ifdef DEBUG_SLEEP
	if (SDL_ThreadID() != mainThreadId)
		log_add (log_Debug, "SleepThreadUntil called from non-main "
				"thread.\n");
#endif  /* DEBUG_SLEEP */

	for (;;) {
		uint32 nextTimeMs;
		TimeCount nextTime;
		TimeCount now;

		Async_process ();

		now = GetTimeCounter ();
		if (wakeTime <= now)
			return;
		
		nextTimeMs = Async_timeBeforeNextMs ();
		nextTime = (nextTimeMs / 1000) * ONE_SECOND +
				((nextTimeMs % 1000) * ONE_SECOND / 1000);
				// Overflow-safe conversion.
		if (wakeTime < nextTime)
			nextTime = wakeTime;

		NativeSleepThreadUntil (nextTime);
	}
}

void
TaskSwitch (void)
{
	NativeTaskSwitch ();
}

void
DestroyMutex (Mutex sem)
{
	NativeDestroyMutex (sem);
}

void
LockMutex (Mutex sem)
{
	NativeLockMutex (sem);
}

void
UnlockMutex (Mutex sem)
{
	NativeUnlockMutex (sem);
}

void
DestroySemaphore (Semaphore sem)
{
	NativeDestroySemaphore (sem);
}

void
SetSemaphore (Semaphore sem)
{
	NativeSetSemaphore (sem);
}

void
ClearSemaphore (Semaphore sem)
{
	NativeClearSemaphore (sem);
}

void
DestroyCondVar (CondVar cv)
{
	NativeDestroyCondVar (cv);
}

void
WaitCondVar (CondVar cv)
{
	NativeWaitCondVar (cv);
}

void
SignalCondVar (CondVar cv)
{
	NativeSignalCondVar (cv);
}

void
BroadcastCondVar (CondVar cv)
{
	NativeBroadcastCondVar (cv);
}

void
DestroyRecursiveMutex (RecursiveMutex mutex)
{
	NativeDestroyRecursiveMutex (mutex);
}

void
LockRecursiveMutex (RecursiveMutex mutex)
{
	NativeLockRecursiveMutex (mutex);
}

void
UnlockRecursiveMutex (RecursiveMutex mutex)
{
	NativeUnlockRecursiveMutex (mutex);
}

int
GetRecursiveMutexDepth (RecursiveMutex mutex)
{
	return NativeGetRecursiveMutexDepth (mutex);
}