File: as_thread.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (426 lines) | stat: -rw-r--r-- 11,685 bytes parent folder | download | duplicates (3)
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
/*
   AngelCode Scripting Library
   Copyright (c) 2003-2014 Andreas Jonsson

   This software is provided 'as-is', without any express or implied
   warranty. In no event will the authors be held liable for any
   damages arising from the use of this software.

   Permission is granted to anyone to use this software for any
   purpose, including commercial applications, and to alter it and
   redistribute it freely, subject to the following restrictions:

   1. The origin of this software must not be misrepresented; you
      must not claim that you wrote the original software. If you use
      this software in a product, an acknowledgment in the product
      documentation would be appreciated but is not required.

   2. Altered source versions must be plainly marked as such, and
      must not be misrepresented as being the original software.

   3. This notice may not be removed or altered from any source
      distribution.

   The original version of this library can be located at:
   http://www.angelcode.com/angelscript/

   Andreas Jonsson
   andreas@angelcode.com
*/



//
// as_thread.cpp
//
// Functions for multi threading support
//

#include "as_config.h"
#include "as_thread.h"
#include "as_atomic.h"

BEGIN_AS_NAMESPACE

//=======================================================================

// Singleton
static asCThreadManager *threadManager = 0;

//======================================================================

// Global API functions
extern "C"
{

	AS_API int asThreadCleanup() {
		return asCThreadManager::CleanupLocalData();
	}

	AS_API asIThreadManager *asGetThreadManager() {
		return threadManager;
	}

	AS_API int asPrepareMultithread(asIThreadManager *externalThreadMgr) {
		return asCThreadManager::Prepare(externalThreadMgr);
	}

	AS_API void asUnprepareMultithread() {
		asCThreadManager::Unprepare();
	}

	AS_API void asAcquireExclusiveLock() {
		if (threadManager) {
			ACQUIREEXCLUSIVE(threadManager->appRWLock);
		}
	}

	AS_API void asReleaseExclusiveLock() {
		if (threadManager) {
			RELEASEEXCLUSIVE(threadManager->appRWLock);
		}
	}

	AS_API void asAcquireSharedLock() {
		if (threadManager) {
			ACQUIRESHARED(threadManager->appRWLock);
		}
	}

	AS_API void asReleaseSharedLock() {
		if (threadManager) {
			RELEASESHARED(threadManager->appRWLock);
		}
	}

}

//======================================================================

#if !defined(AS_NO_THREADS) && defined(_MSC_VER) && defined(AS_WINDOWS_THREADS) && (WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
__declspec(thread) asCThreadLocalData *asCThreadManager::tld = 0;
#endif

asCThreadManager::asCThreadManager() {
	// We're already in the critical section when this function is called

#ifdef AS_NO_THREADS
	tld = 0;
#else
	// Allocate the thread local storage
#if defined AS_POSIX_THREADS
	pthread_key_t pKey;
	pthread_key_create(&pKey, 0);
	tlsKey = (asDWORD)pKey;
#elif defined AS_WINDOWS_THREADS
#if defined(_MSC_VER) && (WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
	tld = 0;
#else
	tlsKey = (asDWORD)TlsAlloc();
#endif
#endif
#endif
	refCount = 1;
}

int asCThreadManager::Prepare(asIThreadManager *externalThreadMgr) {
	// Don't allow an external thread manager if there
	// is already a thread manager defined
	if (externalThreadMgr && threadManager)
		return asINVALID_ARG;

	// The critical section cannot be declared globally, as there is no
	// guarantee for the order in which global variables are initialized
	// or uninitialized.

	// For this reason it's not possible to prevent two threads from calling
	// AddRef at the same time, so there is a chance for a race condition here.

	// To avoid the race condition when the thread manager is first created,
	// the application must make sure to call the global asPrepareForMultiThread()
	// in the main thread before any other thread creates a script engine.
	if (threadManager == 0 && externalThreadMgr == 0)
		threadManager = asNEW(asCThreadManager);
	else {
		// If an application uses different dlls each dll will get it's own memory
		// space for global variables. If multiple dlls then uses AngelScript's
		// global thread support functions it is then best to share the thread
		// manager to make sure all dlls use the same critical section.
		if (externalThreadMgr)
			threadManager = reinterpret_cast<asCThreadManager *>(externalThreadMgr);

		ENTERCRITICALSECTION(threadManager->criticalSection);
		threadManager->refCount++;
		LEAVECRITICALSECTION(threadManager->criticalSection);
	}

	// Success
	return 0;
}

void asCThreadManager::Unprepare() {
	asASSERT(threadManager);

	if (threadManager == 0)
		return;

	// It's necessary to protect this section so no
	// other thread attempts to call AddRef or Release
	// while clean up is in progress.
	ENTERCRITICALSECTION(threadManager->criticalSection);
	if (--threadManager->refCount == 0) {
		// Make sure the local data is destroyed, at least for the current thread
		CleanupLocalData();

		// As the critical section will be destroyed together
		// with the thread manager we must first clear the global
		// variable in case a new thread manager needs to be created;
		asCThreadManager *mgr = threadManager;
		threadManager = 0;

		// Leave the critical section before it is destroyed
		LEAVECRITICALSECTION(mgr->criticalSection);

		asDELETE(mgr, asCThreadManager);
	} else
		LEAVECRITICALSECTION(threadManager->criticalSection);
}

asCThreadManager::~asCThreadManager() {
#ifndef AS_NO_THREADS
	// Deallocate the thread local storage
#if defined AS_POSIX_THREADS
	pthread_key_delete((pthread_key_t)tlsKey);
#elif defined AS_WINDOWS_THREADS
#if defined(_MSC_VER) && (WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
	tld = 0;
#else
	TlsFree((DWORD)tlsKey);
#endif
#endif
#else
	if (tld) {
		asDELETE(tld, asCThreadLocalData);
	}
	tld = 0;
#endif
}

int asCThreadManager::CleanupLocalData() {
	if (threadManager == 0)
		return 0;

#ifndef AS_NO_THREADS
#if defined AS_POSIX_THREADS
	asCThreadLocalData *tld = (asCThreadLocalData *)pthread_getspecific((pthread_key_t)threadManager->tlsKey);
#elif defined AS_WINDOWS_THREADS
#if !defined(_MSC_VER) || !(WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
	asCThreadLocalData *tld = (asCThreadLocalData *)TlsGetValue((DWORD)threadManager->tlsKey);
#endif
#endif

	if (tld == 0)
		return 0;

	if (tld->activeContexts.GetLength() == 0) {
		asDELETE(tld, asCThreadLocalData);
#if defined AS_POSIX_THREADS
		pthread_setspecific((pthread_key_t)threadManager->tlsKey, 0);
#elif defined AS_WINDOWS_THREADS
#if defined(_MSC_VER) && (WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
		tld = 0;
#else
		TlsSetValue((DWORD)threadManager->tlsKey, 0);
#endif
#endif
		return 0;
	} else
		return asCONTEXT_ACTIVE;

#else
	if (threadManager->tld) {
		if (threadManager->tld->activeContexts.GetLength() == 0) {
			asDELETE(threadManager->tld, asCThreadLocalData);
			threadManager->tld = 0;
		} else
			return asCONTEXT_ACTIVE;
	}
	return 0;
#endif
}

asCThreadLocalData *asCThreadManager::GetLocalData() {
	if (threadManager == 0)
		return 0;

#ifndef AS_NO_THREADS
#if defined AS_POSIX_THREADS
	asCThreadLocalData *tld = (asCThreadLocalData *)pthread_getspecific((pthread_key_t)threadManager->tlsKey);
	if (tld == 0) {
		tld = asNEW(asCThreadLocalData)();
		pthread_setspecific((pthread_key_t)threadManager->tlsKey, tld);
	}
#elif defined AS_WINDOWS_THREADS
#if defined(_MSC_VER) && (WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
	if (tld == 0)
		tld = asNEW(asCThreadLocalData)();
#else
	asCThreadLocalData *tld = (asCThreadLocalData *)TlsGetValue((DWORD)threadManager->tlsKey);
	if (tld == 0) {
		tld = asNEW(asCThreadLocalData)();
		TlsSetValue((DWORD)threadManager->tlsKey, tld);
	}
#endif
#endif

	return tld;
#else
	if (threadManager->tld == 0)
		threadManager->tld = asNEW(asCThreadLocalData)();

	return threadManager->tld;
#endif
}

//=========================================================================

asCThreadLocalData::asCThreadLocalData() {
}

asCThreadLocalData::~asCThreadLocalData() {
}

//=========================================================================

#ifndef AS_NO_THREADS
asCThreadCriticalSection::asCThreadCriticalSection() {
#if defined AS_POSIX_THREADS
	pthread_mutex_init(&cs, 0);
#elif defined AS_WINDOWS_THREADS
#if defined(_MSC_VER) && (WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
	// Only the Ex version is available on Windows Store
	InitializeCriticalSectionEx(&cs, 4000, 0);
#else
	// Only the non-Ex version is available on WinXP and older
	// MinGW also only defines this version
	InitializeCriticalSection(&cs);
#endif
#endif
}

asCThreadCriticalSection::~asCThreadCriticalSection() {
#if defined AS_POSIX_THREADS
	pthread_mutex_destroy(&cs);
#elif defined AS_WINDOWS_THREADS
	DeleteCriticalSection(&cs);
#endif
}

void asCThreadCriticalSection::Enter() {
#if defined AS_POSIX_THREADS
	pthread_mutex_lock(&cs);
#elif defined AS_WINDOWS_THREADS
	EnterCriticalSection(&cs);
#endif
}

void asCThreadCriticalSection::Leave() {
#if defined AS_POSIX_THREADS
	pthread_mutex_unlock(&cs);
#elif defined AS_WINDOWS_THREADS
	LeaveCriticalSection(&cs);
#endif
}

bool asCThreadCriticalSection::TryEnter() {
#if defined AS_POSIX_THREADS
	return !pthread_mutex_trylock(&cs);
#elif defined AS_WINDOWS_THREADS
	return TryEnterCriticalSection(&cs) ? true : false;
#else
	return true;
#endif
}

asCThreadReadWriteLock::asCThreadReadWriteLock() {
#if defined AS_POSIX_THREADS
	int r = pthread_rwlock_init(&lock, 0);
	asASSERT(r == 0);
	UNUSED_VAR(r);
#elif defined AS_WINDOWS_THREADS
#if defined(_MSC_VER) && (WINAPI_FAMILY & WINAPI_FAMILY_PHONE_APP)
	// Only the Ex versions are available on Windows Store

	// Create a semaphore to allow up to maxReaders simultaneous readers
	readLocks = CreateSemaphoreExW(NULL, maxReaders, maxReaders, 0, 0, 0);
	// Create a critical section to synchronize writers
	InitializeCriticalSectionEx(&writeLock, 4000, 0);
#else
	readLocks = CreateSemaphoreW(NULL, maxReaders, maxReaders, 0);
	InitializeCriticalSection(&writeLock);
#endif
#endif
}

asCThreadReadWriteLock::~asCThreadReadWriteLock() {
#if defined AS_POSIX_THREADS
	pthread_rwlock_destroy(&lock);
#elif defined AS_WINDOWS_THREADS
	DeleteCriticalSection(&writeLock);
	CloseHandle(readLocks);
#endif
}

void asCThreadReadWriteLock::AcquireExclusive() {
#if defined AS_POSIX_THREADS
	pthread_rwlock_wrlock(&lock);
#elif defined AS_WINDOWS_THREADS
	// Synchronize writers, so only one tries to lock out the readers
	EnterCriticalSection(&writeLock);

	// Lock all reader out from the semaphore. Do this one by one,
	// so the lock doesn't have to wait until there are no readers at all.
	// If we try to lock all at once it is quite possible the writer will
	// never succeed.
	for (asUINT n = 0; n < maxReaders; n++)
		WaitForSingleObjectEx(readLocks, INFINITE, FALSE);

	// Allow another writer to lock. It will only be able to
	// lock the readers when this writer releases them anyway.
	LeaveCriticalSection(&writeLock);
#endif
}

void asCThreadReadWriteLock::ReleaseExclusive() {
#if defined AS_POSIX_THREADS
	pthread_rwlock_unlock(&lock);
#elif defined AS_WINDOWS_THREADS
	// Release all readers at once
	ReleaseSemaphore(readLocks, maxReaders, 0);
#endif
}

void asCThreadReadWriteLock::AcquireShared() {
#if defined AS_POSIX_THREADS
	pthread_rwlock_rdlock(&lock);
#elif defined AS_WINDOWS_THREADS
	// Lock a reader slot
	WaitForSingleObjectEx(readLocks, INFINITE, FALSE);
#endif
}

void asCThreadReadWriteLock::ReleaseShared() {
#if defined AS_POSIX_THREADS
	pthread_rwlock_unlock(&lock);
#elif defined AS_WINDOWS_THREADS
	// Release the reader slot
	ReleaseSemaphore(readLocks, 1, 0);
#endif
}

#endif

//========================================================================

END_AS_NAMESPACE