forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadtools.cpp
3269 lines (2708 loc) · 75.9 KB
/
threadtools.cpp
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========== Copyright 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "tier0/platform.h"
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0403
#include <windows.h>
#endif
#ifdef _WIN32
#include <process.h>
#include <Mmsystem.h>
#pragma comment(lib, "winmm.lib")
#include "tier0/vcrmode.h"
#elif POSIX
#include <sched.h>
#include <exception>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
#include <sys/time.h>
#define GetLastError() errno
typedef void *LPVOID;
#if !defined(OSX)
#if defined(ANDROID)
#include <fcntl.h>
#include <unistd.h>
#else
#include <sys/fcntl.h>
#include <sys/unistd.h>
#endif
#define sem_unlink( arg )
#define OS_TO_PTHREAD(x) (x)
#else
#define pthread_yield pthread_yield_np
#include <mach/thread_act.h>
#include <mach/mach.h>
#define OS_TO_PTHREAD(x) pthread_from_mach_thread_np( x )
#endif // !OSX
#ifdef PLATFORM_BSD
# undef OS_TO_PTRHEAD
# define OS_TO_PTHREAD(x) (pthread_t)(x)
#endif
#endif
#ifndef _PS3
#include <memory.h>
#endif
#include "tier0/minidump.h"
#include "tier0/threadtools.h"
#include "tier0/dynfunction.h"
#ifdef _X360
#include "xbox/xbox_win32stubs.h"
#endif
#include <map>
// Must be last header...
#include "tier0/memdbgon.h"
#ifdef _PS3
#include "ps3/ps3_win32stubs.h"
#define NEW_WAIT_FOR_MULTIPLE_OBJECTS
bool gbCheckNotMultithreaded = true;
extern "C" void(*g_pfnPushMarker)( const char * pName );
extern "C" void(*g_pfnPopMarker)();
#endif
#define THREADS_DEBUG 1
#define DEBUG_ERROR(XX) Assert(0)
// Need to ensure initialized before other clients call in for main thread ID
#ifdef _WIN32
#pragma warning(disable:4073)
#pragma init_seg(lib)
#endif
#ifdef _WIN32
ASSERT_INVARIANT(TT_SIZEOF_CRITICALSECTION == sizeof(CRITICAL_SECTION));
ASSERT_INVARIANT(TT_INFINITE == INFINITE);
#endif
// thread creation counter.
// this is used to provide a unique threadid for each running thread in g_nThreadID ( a thread local variable ).
const int MAX_THREAD_IDS = 128;
static volatile bool s_bThreadIDAllocated[MAX_THREAD_IDS];
#if defined(_PS3)
#include "tls_ps3.h"
#else
DLL_CLASS_EXPORT CTHREADLOCALINT g_nThreadID;
#endif
static CThreadFastMutex s_ThreadIDMutex;
PLATFORM_INTERFACE void AllocateThreadID( void )
{
AUTO_LOCK( s_ThreadIDMutex );
for( int i = 1; i < MAX_THREAD_IDS; i++ )
{
if ( ! s_bThreadIDAllocated[i] )
{
g_nThreadID = i;
s_bThreadIDAllocated[i] = true;
return;
}
}
Error( "Out of thread ids. Decrease the number of threads or increase MAX_THREAD_IDS\n" );
}
PLATFORM_INTERFACE void FreeThreadID( void )
{
AUTO_LOCK( s_ThreadIDMutex );
int nThread = g_nThreadID;
if ( nThread )
s_bThreadIDAllocated[nThread] = false;
}
//-----------------------------------------------------------------------------
// Simple thread functions.
// Because _beginthreadex uses stdcall, we need to convert to cdecl
//-----------------------------------------------------------------------------
struct ThreadProcInfo_t
{
ThreadProcInfo_t( ThreadFunc_t pfnThread, void *pParam )
: pfnThread( pfnThread),
pParam( pParam )
{
}
ThreadFunc_t pfnThread;
void * pParam;
};
//---------------------------------------------------------
#ifdef _WIN32
static DWORD WINAPI ThreadProcConvert( void *pParam )
{
ThreadProcInfo_t info = *((ThreadProcInfo_t *)pParam);
AllocateThreadID();
delete ((ThreadProcInfo_t *)pParam);
unsigned nRet = (*info.pfnThread)(info.pParam);
FreeThreadID();
return nRet;
}
#elif defined( PS3 )
union ThreadProcInfoUnion_t
{
struct Val_t
{
ThreadFunc_t pfnThread;
void * pParam;
}
val;
uint64_t val64;
};
static void ThreadProcConvertUnion( uint64_t param )
{
COMPILE_TIME_ASSERT( sizeof( ThreadProcInfoUnion_t ) == 8 );
ThreadProcInfoUnion_t info;
info.val64 = param;
AllocateThreadID();
unsigned nRet = (*info.val.pfnThread)(info.val.pParam);
FreeThreadID();
sys_ppu_thread_exit( nRet );
}
static void* ThreadProcConvert( void *pParam )
{
ThreadProcInfo_t info = *((ThreadProcInfo_t *)pParam);
AllocateThreadID();
delete ((ThreadProcInfo_t *)pParam);
unsigned nRet = (*info.pfnThread)(info.pParam);
FreeThreadID();
return ( void * ) nRet;
}
#else
static void* ThreadProcConvert( void *pParam )
{
ThreadProcInfo_t info = *((ThreadProcInfo_t *)pParam);
AllocateThreadID();
delete ((ThreadProcInfo_t *)pParam);
unsigned nRet = (*info.pfnThread)(info.pParam);
FreeThreadID();
return ( void * ) (uintp) nRet;
}
#endif
#if defined( _PS3 )
/*******************************************************************************
* Thread Local Storage globals and functions
*******************************************************************************/
#ifndef _PS3
__thread void *gTLSValues[ MAX_TLS_VALUES ] = { NULL };
__thread bool gTLSFlags[ MAX_TLS_VALUES ] = { false };
__thread bool gbWaitObjectsCreated = false;
__thread sys_semaphore_t gWaitObjectsSemaphore;
#endif // !_PS3
static char gThreadName[28] = "";
// Simple TLS allocator. Linearly searches for a free slot.
uint32 TlsAlloc()
{
for ( int i = 0; i < MAX_TLS_VALUES; ++i )
{
if ( !gTLSFlags[i] )
{
gTLSFlags[i] = true;
return i;
}
}
#ifdef _PS3
DEBUG_ERROR("TlsAlloc(): Out of TLS\n");
#endif
return 0xFFFFFFFF;
}
void TlsFree( uint32 index )
{
gTLSValues[ index ] = NULL;
gTLSFlags[ index ] = false;
}
void *TlsGetValue( uint32 index )
{
return gTLSValues[ index ];
}
void TlsSetValue( uint32 index, void *pValue )
{
gTLSValues[ index ] = pValue;
}
#endif //_PS3
#ifdef _WIN32
class CThreadHandleToIDMap
{
public:
HANDLE m_hThread;
uint m_ThreadID;
CThreadHandleToIDMap *m_pNext;
};
static CThreadHandleToIDMap *g_pThreadHandleToIDMaps = NULL;
static CThreadMutex g_ThreadHandleToIDMapMutex;
static volatile int g_nThreadHandleToIDMaps = 0;
static void AddThreadHandleToIDMap( HANDLE hThread, uint threadID )
{
if ( !hThread )
return;
// Remember this handle/id combo.
CThreadHandleToIDMap *pMap = new CThreadHandleToIDMap;
pMap->m_hThread = hThread;
pMap->m_ThreadID = threadID;
// Add it to the global list.
g_ThreadHandleToIDMapMutex.Lock();
pMap->m_pNext = g_pThreadHandleToIDMaps;
g_pThreadHandleToIDMaps = pMap;
++g_nThreadHandleToIDMaps;
g_ThreadHandleToIDMapMutex.Unlock();
if ( g_nThreadHandleToIDMaps > 500 )
Error( "ThreadHandleToIDMap overflow." );
}
// This assumes you've got g_ThreadHandleToIDMapMutex locked!!
static bool InternalLookupHandleToThreadIDMap( HANDLE hThread, CThreadHandleToIDMap* &pMap, CThreadHandleToIDMap** &ppPrev )
{
ppPrev = &g_pThreadHandleToIDMaps;
for ( pMap=g_pThreadHandleToIDMaps; pMap; pMap=pMap->m_pNext )
{
if ( pMap->m_hThread == hThread )
return true;
ppPrev = &pMap->m_pNext;
}
return false;
}
static void RemoveThreadHandleToIDMap( HANDLE hThread )
{
if ( !hThread )
return;
CThreadHandleToIDMap *pMap, **ppPrev;
g_ThreadHandleToIDMapMutex.Lock();
if ( g_nThreadHandleToIDMaps <= 0 )
Error( "ThreadHandleToIDMap underflow." );
if ( InternalLookupHandleToThreadIDMap( hThread, pMap, ppPrev ) )
{
*ppPrev = pMap->m_pNext;
delete pMap;
--g_nThreadHandleToIDMaps;
}
g_ThreadHandleToIDMapMutex.Unlock();
}
static uint LookupThreadIDFromHandle( HANDLE hThread )
{
if ( hThread == NULL || hThread == GetCurrentThread() )
return GetCurrentThreadId();
float flStartTime = Plat_FloatTime();
while ( Plat_FloatTime() - flStartTime < 2 )
{
CThreadHandleToIDMap *pMap, **ppPrev;
g_ThreadHandleToIDMapMutex.Lock();
bool bRet = InternalLookupHandleToThreadIDMap( hThread, pMap, ppPrev );
g_ThreadHandleToIDMapMutex.Unlock();
if ( bRet )
return pMap->m_ThreadID;
// We should only get here if a thread that is just starting up is currently in AddThreadHandleToIDMap.
// Give up the timeslice and try again.
ThreadSleep( 1 );
}
Assert( !"LookupThreadIDFromHandle failed!" );
Warning( "LookupThreadIDFromHandle couldn't find thread ID for handle." );
return 0;
}
#endif
//---------------------------------------------------------
ThreadHandle_t * CreateTestThreads( ThreadFunc_t fnThread, int numThreads, int nProcessorsToDistribute )
{
ThreadHandle_t *pHandles = (new ThreadHandle_t[numThreads+1]) + 1;
pHandles[-1] = (ThreadHandle_t)INT_TO_POINTER( numThreads );
for( int i = 0; i < numThreads; ++i )
{
//TestThreads();
ThreadHandle_t hThread;
const unsigned int nDefaultStackSize = 64 * 1024; // this stack size is used in case stackSize == 0
hThread = CreateSimpleThread( fnThread, INT_TO_POINTER( i ), nDefaultStackSize );
if ( nProcessorsToDistribute )
{
int32 mask = 1 << (i % nProcessorsToDistribute);
ThreadSetAffinity( hThread, mask );
}
/*
ThreadProcInfoUnion_t info;
info.val.pfnThread = fnThread;
info.val.pParam = (void*)(i);
if ( int nError = sys_ppu_thread_create( &hThread, ThreadProcConvertUnion, info.val64, 1001, nDefaultStackSize, SYS_PPU_THREAD_CREATE_JOINABLE, "SimpleThread" ) != CELL_OK )
{
printf( "PROBLEM!\n" );
Error( "Cannot create thread, error %d\n", nError );
return 0;
}
*/
//ThreadHandle_t hThread = CreateSimpleThread( fnThread, (void*)i );
pHandles[i] = hThread;
}
// printf("Finishinged CreateTestThreads(%p,%d)\n", (void*)fnThread, numThreads );
return pHandles;
}
void JoinTestThreads( ThreadHandle_t *pHandles )
{
int nCount = POINTER_TO_INT( (uintp)pHandles[-1] );
// printf("Joining test threads @%p[%d]:\n", pHandles, nCount );
// for( int i = 0; i < nCount; ++i )
// {
// printf(" %p,\n", (void*)pHandles[i] );
// }
for( int i = 0; i < nCount; ++i )
{
// printf( "Joining %p", (void*) pHandles[i] );
// if( !i ) sys_timer_usleep(100000);
ThreadJoin( pHandles[i] );
ReleaseThreadHandle( pHandles[i] );
}
delete[]( pHandles - 1 );
}
ThreadHandle_t CreateSimpleThread( ThreadFunc_t pfnThread, void *pParam, unsigned stackSize )
{
#ifdef _WIN32
DWORD threadID;
HANDLE hThread = (HANDLE)CreateThread( NULL, stackSize, ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ), stackSize ? STACK_SIZE_PARAM_IS_A_RESERVATION : 0, &threadID );
AddThreadHandleToIDMap( hThread, threadID );
return (ThreadHandle_t)hThread;
#elif PS3
//TestThreads();
ThreadHandle_t th;
ThreadProcInfoUnion_t info;
info.val.pfnThread = pfnThread;
info.val.pParam = pParam;
const unsigned int nDefaultStackSize = 64 * 1024; // this stack size is used in case stackSize == 0
if ( sys_ppu_thread_create( &th, ThreadProcConvertUnion, info.val64, 1001, stackSize ? stackSize : nDefaultStackSize, SYS_PPU_THREAD_CREATE_JOINABLE, "SimpleThread" ) != CELL_OK )
{
AssertMsg1( 0, "Failed to create thread (error 0x%x)", errno );
return 0;
}
return th;
#elif POSIX
pthread_t tid;
pthread_create( &tid, NULL, ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ) );
return ( ThreadHandle_t ) tid;
#else
Assert( 0 );
DebuggerBreak();
return 0;
#endif
}
ThreadHandle_t CreateSimpleThread( ThreadFunc_t pfnThread, void *pParam, ThreadId_t *pID, unsigned stackSize )
{
#ifdef _WIN32
DWORD threadID;
HANDLE hThread = (HANDLE)CreateThread( NULL, stackSize, ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ), stackSize ? STACK_SIZE_PARAM_IS_A_RESERVATION : 0, &threadID );
if( pID )
*pID = (ThreadId_t)threadID;
AddThreadHandleToIDMap( hThread, threadID );
return (ThreadHandle_t)hThread;
#elif POSIX
pthread_t tid;
pthread_create( &tid, NULL, ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ) );
if( pID )
*pID = (ThreadId_t)tid;
return ( ThreadHandle_t ) tid;
#else
Assert( 0 );
DebuggerBreak();
return 0;
#endif
}
bool ReleaseThreadHandle( ThreadHandle_t hThread )
{
#ifdef _WIN32
bool bRetVal = ( CloseHandle( hThread ) != 0 );
RemoveThreadHandleToIDMap( (HANDLE)hThread );
return bRetVal;
#else
return true;
#endif
}
//-----------------------------------------------------------------------------
//
// Wrappers for other simple threading operations
//
//-----------------------------------------------------------------------------
void ThreadSleep(unsigned nMilliseconds)
{
#ifdef _WIN32
#ifdef _WIN32_PC
static bool bInitialized = false;
if ( !bInitialized )
{
bInitialized = true;
// Set the timer resolution to 1 ms (default is 10.0, 15.6, 2.5, 1.0 or
// some other value depending on hardware and software) so that we can
// use Sleep( 1 ) to avoid wasting CPU time without missing our frame
// rate.
timeBeginPeriod( 1 );
}
#endif
Sleep( nMilliseconds );
#elif PS3
if( nMilliseconds == 0 )
{
// sys_ppu_thread_yield doesn't seem to function properly, so sleep instead.
// sys_timer_usleep( 60 );
sys_ppu_thread_yield();
}
else
{
sys_timer_usleep( nMilliseconds * 1000 );
}
#elif defined(POSIX)
usleep( nMilliseconds * 1000 );
#endif
}
//-----------------------------------------------------------------------------
void ThreadNanoSleep(unsigned ns)
{
#ifdef _WIN32
// ceil
Sleep( ( ns + 999 ) / 1000 );
#elif PS3
sys_timer_usleep( ns );
#elif defined(POSIX)
struct timespec tm;
tm.tv_sec = 0;
tm.tv_nsec = ns;
nanosleep( &tm, NULL );
#endif
}
//-----------------------------------------------------------------------------
#ifndef ThreadGetCurrentId
ThreadId_t ThreadGetCurrentId()
{
#ifdef _WIN32
return GetCurrentThreadId();
#elif defined( _PS3 )
sys_ppu_thread_t th = 0;
sys_ppu_thread_get_id( &th );
return th;
#elif defined(POSIX)
return (ThreadId_t)pthread_self();
#else
Assert(0);
DebuggerBreak();
return 0;
#endif
}
#endif
//-----------------------------------------------------------------------------
ThreadHandle_t ThreadGetCurrentHandle()
{
#ifdef _WIN32
return (ThreadHandle_t)GetCurrentThread();
#elif defined( _PS3 )
sys_ppu_thread_t th = 0;
sys_ppu_thread_get_id( &th );
return th;
#elif defined(POSIX)
return (ThreadHandle_t)pthread_self();
#else
Assert(0);
DebuggerBreak();
return 0;
#endif
}
// On PS3, this will return true for zombie threads
bool ThreadIsThreadIdRunning( ThreadId_t uThreadId )
{
#ifdef _WIN32
bool bRunning = true;
HANDLE hThread = ::OpenThread( THREAD_QUERY_INFORMATION , false, uThreadId );
if ( hThread )
{
DWORD dwExitCode;
if( !::GetExitCodeThread( hThread, &dwExitCode ) || dwExitCode != STILL_ACTIVE )
bRunning = false;
CloseHandle( hThread );
}
else
{
bRunning = false;
}
return bRunning;
#elif defined( _PS3 )
// will return CELL_OK for zombie threads
int priority;
return (sys_ppu_thread_get_priority( uThreadId, &priority ) == CELL_OK );
#elif defined(POSIX)
int iResult = pthread_kill( OS_TO_PTHREAD(uThreadId), 0 );
if ( iResult == 0 )
return true;
return false;
#endif
}
//-----------------------------------------------------------------------------
int ThreadGetPriority( ThreadHandle_t hThread )
{
if ( !hThread )
{
hThread = ThreadGetCurrentHandle();
}
#ifdef _WIN32
return ::GetThreadPriority( (HANDLE)hThread );
#elif defined( _PS3 )
int iPri = 0;
sys_ppu_thread_get_priority( hThread, &iPri );
return iPri;
#else
return 0;
#endif
}
//-----------------------------------------------------------------------------
bool ThreadSetPriority( ThreadHandle_t hThread, int priority )
{
if ( !hThread )
{
hThread = ThreadGetCurrentHandle();
}
#ifdef _WIN32
return ( SetThreadPriority(hThread, priority) != 0 );
#elif defined( _PS3 )
int retval = sys_ppu_thread_set_priority( hThread, priority );
return retval >= CELL_OK;
#elif defined(POSIX)
struct sched_param thread_param;
thread_param.sched_priority = priority;
//pthread_setschedparam( (pthread_t ) hThread, SCHED_RR, &thread_param );
return true;
#endif
}
//-----------------------------------------------------------------------------
void ThreadSetAffinity( ThreadHandle_t hThread, int nAffinityMask )
{
if ( !hThread )
{
hThread = ThreadGetCurrentHandle();
}
#ifdef _WIN32
SetThreadAffinityMask( hThread, nAffinityMask );
#elif defined(POSIX)
// cpu_set_t cpuSet;
// CPU_ZERO( cpuSet );
// for( int i = 0 ; i < 32; i++ )
// if ( nAffinityMask & ( 1 << i ) )
// CPU_SET( cpuSet, i );
// sched_setaffinity( hThread, sizeof( cpuSet ), &cpuSet );
#endif
}
//-----------------------------------------------------------------------------
#ifndef _X360
ThreadId_t InitMainThread()
{
ThreadSetDebugName( "MainThrd" );
return ThreadGetCurrentId();
}
ThreadId_t g_ThreadMainThreadID = InitMainThread();
bool ThreadInMainThread()
{
return ( ThreadGetCurrentId() == g_ThreadMainThreadID );
}
void DeclareCurrentThreadIsMainThread()
{
g_ThreadMainThreadID = ThreadGetCurrentId();
}
#else
byte *InitMainThread()
{
byte b;
return AlignValue( &b, 64*1024 );
}
#define STACK_SIZE_360 327680
byte *g_pBaseMainStack = InitMainThread();
byte *g_pLimitMainStack = InitMainThread() - STACK_SIZE_360;
#endif
//-----------------------------------------------------------------------------
bool ThreadJoin( ThreadHandle_t hThread, unsigned timeout )
{
if ( !hThread )
{
return false;
}
#ifdef _WIN32
DWORD dwWait = WaitForSingleObject( (HANDLE)hThread, timeout );
if ( dwWait == WAIT_TIMEOUT)
return false;
if ( dwWait != WAIT_OBJECT_0 && ( dwWait != WAIT_FAILED && GetLastError() != 0 ) )
{
Assert( 0 );
return false;
}
#elif defined( _PS3 )
uint64 uiExitCode = 0;
int retval = sys_ppu_thread_join( hThread, &uiExitCode );
return ( retval >= CELL_OK );
#elif defined(POSIX)
if ( pthread_join( (pthread_t)hThread, NULL ) != 0 )
return false;
#else
Assert(0);
DebuggerBreak();
#endif
return true;
}
//-----------------------------------------------------------------------------
void ThreadSetDebugName( ThreadHandle_t hThread, const char *pszName )
{
#ifdef WIN32
if ( Plat_IsInDebugSession() )
{
#define MS_VC_EXCEPTION 0x406d1388
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // must be 0x1000
LPCSTR szName; // pointer to name (in same addr space)
DWORD dwThreadID; // thread ID (-1 caller thread)
DWORD dwFlags; // reserved for future use, most be zero
} THREADNAME_INFO;
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = pszName;
info.dwThreadID = LookupThreadIDFromHandle( hThread );
if ( info.dwThreadID != 0 )
{
info.dwFlags = 0;
__try
{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info);
}
__except (EXCEPTION_CONTINUE_EXECUTION)
{
}
}
}
#endif
}
//-----------------------------------------------------------------------------
#ifdef _WIN32
ASSERT_INVARIANT( TW_FAILED == WAIT_FAILED );
ASSERT_INVARIANT( TW_TIMEOUT == WAIT_TIMEOUT );
ASSERT_INVARIANT( WAIT_OBJECT_0 == 0 );
int ThreadWaitForObjects( int nEvents, const HANDLE *pHandles, bool bWaitAll, unsigned timeout )
{
return VCRHook_WaitForMultipleObjects( nEvents, pHandles, bWaitAll, timeout );
}
#endif
//-----------------------------------------------------------------------------
// Used to thread LoadLibrary on the 360
//-----------------------------------------------------------------------------
static ThreadedLoadLibraryFunc_t s_ThreadedLoadLibraryFunc = 0;
PLATFORM_INTERFACE void SetThreadedLoadLibraryFunc( ThreadedLoadLibraryFunc_t func )
{
s_ThreadedLoadLibraryFunc = func;
}
PLATFORM_INTERFACE ThreadedLoadLibraryFunc_t GetThreadedLoadLibraryFunc()
{
return s_ThreadedLoadLibraryFunc;
}
//-----------------------------------------------------------------------------
//
// CThreadSyncObject (note nothing uses this directly (I think) )
//
//-----------------------------------------------------------------------------
#ifdef _PS3
uint32_t CThreadSyncObject::m_bstaticMutexInitialized = false;
uint32_t CThreadSyncObject::m_bstaticMutexInitializing = false;
sys_lwmutex_t CThreadSyncObject::m_staticMutex;
#endif
CThreadSyncObject::CThreadSyncObject()
#ifdef _WIN32
: m_hSyncObject( NULL ), m_bCreatedHandle(false)
#elif defined(POSIX) && !defined(PS3)
: m_bInitalized( false )
#endif
{
#ifdef _PS3
//Do we nee to initialise the staticMutex?
if (m_bstaticMutexInitialized) return;
//If we are the first thread then create the mutex
if ( cellAtomicCompareAndSwap32(&m_bstaticMutexInitializing, false, true) == false )
{
sys_lwmutex_attribute_t mutexAttr;
sys_lwmutex_attribute_initialize( mutexAttr );
mutexAttr.attr_recursive = SYS_SYNC_RECURSIVE;
int err = sys_lwmutex_create( &m_staticMutex, &mutexAttr );
Assert(err == CELL_OK);
m_bstaticMutexInitialized = true;
}
else
{
//Another thread is already in the process of initialising the mutex, wait for it
while ( !m_bstaticMutexInitialized )
{
// sys_ppu_thread_yield doesn't seem to function properly, so sleep instead.
// sys_timer_usleep( 60 );
sys_ppu_thread_yield();
}
}
#endif
}
//---------------------------------------------------------
CThreadSyncObject::~CThreadSyncObject()
{
#ifdef _WIN32
if ( m_hSyncObject && m_bCreatedHandle )
{
if ( !CloseHandle(m_hSyncObject) )
{
Assert( 0 );
}
}
#elif defined(POSIX) && !defined( PS3 )
if ( m_bInitalized )
{
pthread_cond_destroy( &m_Condition );
pthread_mutex_destroy( &m_Mutex );
m_bInitalized = false;
}
#endif
}
//---------------------------------------------------------
bool CThreadSyncObject::operator!() const
{
#if PS3
return m_bstaticMutexInitialized;
#elif defined( _WIN32 )
return !m_hSyncObject;
#elif defined(POSIX)
return !m_bInitalized;
#endif
}
//---------------------------------------------------------
void CThreadSyncObject::AssertUseable()
{
#ifdef THREADS_DEBUG
#if PS3
AssertMsg( m_bstaticMutexInitialized, "Thread synchronization object is unuseable" );
#elif defined( _WIN32 )
AssertMsg( m_hSyncObject, "Thread synchronization object is unuseable" );
#elif defined(POSIX)
AssertMsg( m_bInitalized, "Thread synchronization object is unuseable" );
#endif
#endif
}
//---------------------------------------------------------
#if defined(_WIN32) || ( defined(POSIX) && !defined( _PS3 ) )
bool CThreadSyncObject::Wait( uint32 dwTimeout )
{
#ifdef THREADS_DEBUG
AssertUseable();
#endif
#ifdef _WIN32
return ( WaitForSingleObject( m_hSyncObject, dwTimeout ) == WAIT_OBJECT_0 );
#elif defined( POSIX ) && !defined( PS3 )
pthread_mutex_lock( &m_Mutex );
bool bRet = false;
if ( m_cSet > 0 )
{
bRet = true;
m_bWakeForEvent = false;
}
else
{
volatile int ret = 0;
while ( !m_bWakeForEvent && ret != ETIMEDOUT )
{
struct timeval tv;
gettimeofday( &tv, NULL );
volatile struct timespec tm;
uint64 actualTimeout = dwTimeout;
if ( dwTimeout == TT_INFINITE && m_bManualReset )
actualTimeout = 10; // just wait 10 msec at most for manual reset events and loop instead
volatile uint64 nNanoSec = (uint64)tv.tv_usec*1000 + (uint64)actualTimeout*1000000;
tm.tv_sec = tv.tv_sec + nNanoSec /1000000000;
tm.tv_nsec = nNanoSec % 1000000000;
do
{
ret = pthread_cond_timedwait( &m_Condition, &m_Mutex, (const timespec *)&tm );
}
while( ret == EINTR );
bRet = ( ret == 0 );
if ( m_bManualReset )
{
if ( m_cSet )
break;
if ( dwTimeout == TT_INFINITE && ret == ETIMEDOUT )
ret = 0; // force the loop to spin back around
}
}
if ( bRet )
m_bWakeForEvent = false;
}
if ( !m_bManualReset && bRet )
m_cSet = 0;
pthread_mutex_unlock( &m_Mutex );
return bRet;
#endif
}
#endif
uint32 CThreadSyncObject::WaitForMultiple( int nObjects, CThreadSyncObject **ppObjects, bool bWaitAll, uint32 dwTimeout )
{
#if defined( _WIN32 )
CThreadSyncObject *pHandles = (CThreadSyncObject*)stackalloc( sizeof(CThreadSyncObject) * nObjects );
for ( int i=0; i < nObjects; i++ )
{
pHandles[i].m_hSyncObject = ppObjects[i]->m_hSyncObject;
}
return WaitForMultiple( nObjects, pHandles, bWaitAll, dwTimeout );
#else
// TODO: Need a more efficient implementation of this.
uint32 dwStartTime = 0;
if ( dwTimeout != TT_INFINITE )
dwStartTime = Plat_MSTime();
// If bWaitAll = true, then we need to track which ones were triggered.
char *pWasTriggered = NULL;
int nTriggered = 0;
if ( bWaitAll )
{
pWasTriggered = (char*)stackalloc( nObjects );
memset( pWasTriggered, 0, nObjects );
}
while ( 1 )
{
for ( int i=0; i < nObjects; i++ )