forked from mattiasgustavsson/libs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread.h
1505 lines (1020 loc) · 44.3 KB
/
thread.h
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
/*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
thread.h - v0.3 - Cross platform threading functions for C/C++.
Do this:
#define THREAD_IMPLEMENTATION
before you include this file in *one* C/C++ file to create the implementation.
*/
#ifndef thread_h
#define thread_h
#ifndef THREAD_U64
#define THREAD_U64 unsigned long long
#endif
#define THREAD_STACK_SIZE_DEFAULT ( 0 )
#define THREAD_SIGNAL_WAIT_INFINITE ( -1 )
#define THREAD_QUEUE_WAIT_INFINITE ( -1 )
typedef void* thread_id_t;
thread_id_t thread_current_thread_id( void );
void thread_yield( void );
void thread_set_high_priority( void );
void thread_exit( int return_code );
typedef void* thread_ptr_t;
thread_ptr_t thread_create( int (*thread_proc)( void* ), void* user_data, int stack_size );
void thread_destroy( thread_ptr_t thread );
int thread_join( thread_ptr_t thread );
int thread_detach( thread_ptr_t thread );
typedef union thread_mutex_t thread_mutex_t;
void thread_mutex_init( thread_mutex_t* mutex );
void thread_mutex_term( thread_mutex_t* mutex );
void thread_mutex_lock( thread_mutex_t* mutex );
void thread_mutex_unlock( thread_mutex_t* mutex );
typedef union thread_signal_t thread_signal_t;
void thread_signal_init( thread_signal_t* signal );
void thread_signal_term( thread_signal_t* signal );
void thread_signal_raise( thread_signal_t* signal );
int thread_signal_wait( thread_signal_t* signal, int timeout_ms );
typedef union thread_atomic_int_t thread_atomic_int_t;
int thread_atomic_int_load( thread_atomic_int_t* atomic );
void thread_atomic_int_store( thread_atomic_int_t* atomic, int desired );
int thread_atomic_int_inc( thread_atomic_int_t* atomic );
int thread_atomic_int_dec( thread_atomic_int_t* atomic );
int thread_atomic_int_add( thread_atomic_int_t* atomic, int value );
int thread_atomic_int_sub( thread_atomic_int_t* atomic, int value );
int thread_atomic_int_swap( thread_atomic_int_t* atomic, int desired );
int thread_atomic_int_compare_and_swap( thread_atomic_int_t* atomic, int expected, int desired );
typedef union thread_atomic_ptr_t thread_atomic_ptr_t;
void* thread_atomic_ptr_load( thread_atomic_ptr_t* atomic );
void thread_atomic_ptr_store( thread_atomic_ptr_t* atomic, void* desired );
void* thread_atomic_ptr_swap( thread_atomic_ptr_t* atomic, void* desired );
void* thread_atomic_ptr_compare_and_swap( thread_atomic_ptr_t* atomic, void* expected, void* desired );
typedef union thread_timer_t thread_timer_t;
void thread_timer_init( thread_timer_t* timer );
void thread_timer_term( thread_timer_t* timer );
void thread_timer_wait( thread_timer_t* timer, THREAD_U64 nanoseconds );
typedef void* thread_tls_t;
thread_tls_t thread_tls_create( void );
void thread_tls_destroy( thread_tls_t tls );
void thread_tls_set( thread_tls_t tls, void* value );
void* thread_tls_get( thread_tls_t tls );
typedef struct thread_queue_t thread_queue_t;
void thread_queue_init( thread_queue_t* queue, int size, void** values, int count );
void thread_queue_term( thread_queue_t* queue );
int thread_queue_produce( thread_queue_t* queue, void* value, int timeout_ms );
void* thread_queue_consume( thread_queue_t* queue, int timeout_ms );
int thread_queue_count( thread_queue_t* queue );
#endif /* thread_h */
/**
thread.h
========
Cross platform threading functions for C/C++.
Example
-------
Here's a basic sample program which starts a second thread which just waits and prints a message.
#define THREAD_IMPLEMENTATION
#include "thread.h"
#include <stdio.h> // for printf
int thread_proc( void* user_data) {
thread_timer_t timer;
thread_timer_init( &timer );
int count = 0;
thread_atomic_int_t* exit_flag = (thread_atomic_int_t*) user_data;
while( thread_atomic_int_load( exit_flag ) == 0 ) {
printf( "Thread... " );
thread_timer_wait( &timer, 1000000000 ); // sleep for a second
++count;
}
thread_timer_term( &timer );
printf( "Done\n" );
return count;
}
int main( int argc, char** argv ) {
thread_atomic_int_t exit_flag;
thread_atomic_int_store( &exit_flag, 0 );
thread_ptr_t thread = thread_create( thread_proc, &exit_flag, "Example thread", THREAD_STACK_SIZE_DEFAULT );
thread_timer_t timer;
thread_timer_init( &timer );
for( int i = 0; i < 5; ++i ) {
printf( "Main... " );
thread_timer_wait( &timer, 2000000000 ); // sleep for two seconds
}
thread_timer_term( &timer );
thread_atomic_int_store( &exit_flag, 1 ); // signal thread to exit
int retval = thread_join( thread );
printf( "Count: %d\n", retval );
thread_destroy( thread );
return retval;
}
API Documentation
-----------------
thread.h is a single-header library, and does not need any .lib files or other binaries, or any build scripts. To use it,
you just include thread.h to get the API declarations. To get the definitions, you must include thread.h from *one*
single C or C++ file, and #define the symbol `THREAD_IMPLEMENTATION` before you do.
### Customization
thread.h allows for specifying the exact type of 64-bit unsigned integer to be used in its API. By default, it is
defined as `unsigned long long`, but as this is not a standard type on all compilers, you can redefine it by #defining
THREAD_U64 before including thread.h. This is useful if you, for example, use the types from `<stdint.h>` in the rest of
your program, and you want thread.h to use compatible types. In this case, you would include thread.h using the
following code:
#define THREAD_U64 uint64_t
#include "thread.h"
Note that when customizing this data type, you need to use the same definition in every place where you include
thread.h, as it affect the declarations as well as the definitions.
thread_current_thread_id
------------------------
thread_id_t thread_current_thread_id( void )
Returns a unique identifier for the calling thread. After the thread terminates, the id might be reused for new threads.
thread_yield
------------
void thread_yield( void )
Makes the calling thread yield execution to another thread. The operating system controls which thread is switched to.
thread_set_high_priority
------------------------
void thread_set_high_priority( void )
When created, threads are set to run at normal priority. In some rare cases, such as a sound buffer update loop, it can
be necessary to have one thread of your application run on a higher priority than the rest. Calling
`thread_set_high_priority` will raise the priority of the calling thread, giving it a chance to be run more often.
Do not increase the priority of a thread unless you absolutely have to, as it can negatively affect performance if used
without care.
thread_exit
-----------
void thread_exit( int return_code )
Exits the calling thread, as if you had done `return return_code;` from the main body of the thread function.
thread_create
-------------
thread_ptr_t thread_create( int (*thread_proc)( void* ), void* user_data, int stack_size )
Creates a new thread running the `thread_proc` function, passing the `user_data` through to it. The thread will have
the stack size specified in the `stack_size` parameter. To get the operating system default stack size, use the
defined constant `THREAD_STACK_SIZE_DEFAULT`. When returning from the thread_proc function, the value you return can
be received in another thread by calling thread_join. `thread_create` returns a pointer to the thread instance, which
can be used as a parameter to the functions `thread_destroy` and `thread_join`.
thread_destroy
--------------
void thread_destroy( thread_ptr_t thread )
Destroys a thread that was created by calling `thread_create`. Make sure the thread has exited before you attempt to
destroy it. This can be accomplished by calling `thread_join`. It is not possible for force termination of a thread by
calling `thread_destroy`.
thread_join
-----------
int thread_join( thread_ptr_t thread )
Waits for the specified thread to exit. Returns the value which the thread returned when exiting.
thread_detach
-------------
int thread_detach( thread_ptr_t thread )
Marks the thread as detached. When a detached thread terminates, its resources are automatically released back to the
system without the need for another thread to join with the terminated thread.
thread_mutex_init
-----------------
void thread_mutex_init( thread_mutex_t* mutex )
Initializes the specified mutex instance, preparing it for use. A mutex can be used to lock sections of code, such that
it can only be run by one thread at a time.
thread_mutex_term
-----------------
void thread_mutex_term( thread_mutex_t* mutex )
Terminates the specified mutex instance, releasing any system resources held by it.
thread_mutex_lock
-----------------
void thread_mutex_lock( thread_mutex_t* mutex )
Takes an exclusive lock on a mutex. If the lock is already taken by another thread, `thread_mutex_lock` will yield the
calling thread and wait for the lock to become available before returning. The mutex must be initialized by calling
`thread_mutex_init` before it can be locked.
thread_mutex_unlock
-------------------
void thread_mutex_unlock( thread_mutex_t* mutex )
Releases a lock taken by calling `thread_mutex_lock`.
thread_signal_init
------------------
void thread_signal_init( thread_signal_t* signal )
Initializes the specified signal instance, preparing it for use. A signal works like a flag, which can be waited on by
one thread, until it is raised from another thread.
thread_signal_term
------------------
void thread_signal_term( thread_signal_t* signal )
Terminates the specified signal instance, releasing any system resources held by it.
thread_signal_raise
-------------------
void thread_signal_raise( thread_signal_t* signal )
Raise the specified signal. Other threads waiting for the signal will proceed.
thread_signal_wait
------------------
int thread_signal_wait( thread_signal_t* signal, int timeout_ms )
Waits for a signal to be raised, or until `timeout_ms` milliseconds have passed. If the wait timed out, a value of 0 is
returned, otherwise a non-zero value is returned. If the `timeout_ms` parameter is THREAD_SIGNAL_WAIT_INFINITE,
`thread_signal_wait` waits indefinitely.
thread_atomic_int_load
----------------------
int thread_atomic_int_load( thread_atomic_int_t* atomic )
Returns the value of `atomic` as an atomic operation.
thread_atomic_int_store
-----------------------
void thread_atomic_int_store( thread_atomic_int_t* atomic, int desired )
Sets the value of `atomic` as an atomic operation.
thread_atomic_int_inc
---------------------
int thread_atomic_int_inc( thread_atomic_int_t* atomic )
Increments the value of `atomic` by one, as an atomic operation. Returns the value `atomic` had before the operation.
thread_atomic_int_dec
---------------------
int thread_atomic_int_dec( thread_atomic_int_t* atomic )
Decrements the value of `atomic` by one, as an atomic operation. Returns the value `atomic` had before the operation.
thread_atomic_int_add
---------------------
int thread_atomic_int_add( thread_atomic_int_t* atomic, int value )
Adds the specified value to `atomic`, as an atomic operation. Returns the value `atomic` had before the operation.
thread_atomic_int_sub
---------------------
int thread_atomic_int_sub( thread_atomic_int_t* atomic, int value )
Subtracts the specified value to `atomic`, as an atomic operation. Returns the value `atomic` had before the operation.
thread_atomic_int_swap
----------------------
int thread_atomic_int_swap( thread_atomic_int_t* atomic, int desired )
Sets the value of `atomic` as an atomic operation. Returns the value `atomic` had before the operation.
thread_atomic_int_compare_and_swap
----------------------------------
int thread_atomic_int_compare_and_swap( thread_atomic_int_t* atomic, int expected, int desired )
Compares the value of `atomic` to the value of `expected`, and if they match, sets the vale of `atomic` to `desired`,
all as an atomic operation. Returns the value `atomic` had before the operation.
thread_atomic_ptr_load
----------------------
void* thread_atomic_ptr_load( thread_atomic_ptr_t* atomic )
Returns the value of `atomic` as an atomic operation.
thread_atomic_ptr_store
-----------------------
void thread_atomic_ptr_store( thread_atomic_ptr_t* atomic, void* desired )
Sets the value of `atomic` as an atomic operation.
thread_atomic_ptr_swap
----------------------
void* thread_atomic_ptr_swap( thread_atomic_ptr_t* atomic, void* desired )
Sets the value of `atomic` as an atomic operation. Returns the value `atomic` had before the operation.
thread_atomic_ptr_compare_and_swap
----------------------------------
void* thread_atomic_ptr_compare_and_swap( thread_atomic_ptr_t* atomic, void* expected, void* desired )
Compares the value of `atomic` to the value of `expected`, and if they match, sets the vale of `atomic` to `desired`,
all as an atomic operation. Returns the value `atomic` had before the operation.
thread_timer_init
-----------------
void thread_timer_init( thread_timer_t* timer )
Initializes the specified timer instance, preparing it for use. A timer can be used to sleep a thread for a high
precision duration.
thread_timer_term
-----------------
void thread_timer_term( thread_timer_t* timer )
Terminates the specified timer instance, releasing any system resources held by it.
thread_timer_wait
-----------------
void thread_timer_wait( thread_timer_t* timer, THREAD_U64 nanoseconds )
Waits until `nanoseconds` amount of time have passed, before returning.
thread_tls_create
-----------------
thread_tls_t thread_tls_create( void )
Creates a thread local storage (TLS) index. Once created, each thread has its own value for that TLS index, which can
be set or retrieved individually.
thread_tls_destroy
------------------
void thread_tls_destroy( thread_tls_t tls )
Destroys the specified TLS index. No further calls to `thread_tls_set` or `thread_tls_get` are valid after this.
thread_tls_set
--------------
void thread_tls_set( thread_tls_t tls, void* value )
Stores a value in the calling thread's slot for the specified TLS index. Each thread has its own value for each TLS
index.
thread_tls_get
--------------
void* thread_tls_get( thread_tls_t tls )
Retrieves the value from the calling thread's slot for the specified TLS index. Each thread has its own value for each
TLS index.
thread_queue_init
-----------------
void thread_queue_init( thread_queue_t* queue, int size, void** values, int count )
Initializes the specified queue instance, preparing it for use. The queue is a lock-free (but not wait-free)
single-producer/single-consumer queue - it will not acquire any locks as long as there is space for adding or items to
be consume, but will lock and wait when there is not. The `size` parameter specifies the number of elements in the
queue. The `values` parameter is an array of queue slots (`size` elements in length), each being of type `void*`. If
the queue is initially empty, the `count` parameter should be 0, otherwise it indicates the number of entires, from the
start of the `values` array, that the queue is initialized with. The `values` array is not copied, and must remain valid
until `thread_queue_term` is called.
thread_queue_term
-----------------
void thread_queue_term( thread_queue_t* queue )
Terminates the specified queue instance, releasing any system resources held by it.
thread_queue_produce
--------------------
int thread_queue_produce( thread_queue_t* queue, void* value, int timeout_ms )
Adds an element to a single-producer/single-consumer queue. If there is space in the queue to add another element, no
lock will be taken. If the queue is full, calling thread will sleep until an element is consumed from another thread,
before adding the element, or until `timeout_ms` milliseconds have passed. If the wait timed out, a value of 0 is
returned, otherwise a non-zero value is returned. If the `timeout_ms` parameter is THREAD_QUEUE_WAIT_INFINITE,
`thread_queue_produce` waits indefinitely.
thread_queue_consume
--------------------
void* thread_queue_consume( thread_queue_t* queue, int timeout_ms )
Removes an element from a single-producer/single-consumer queue. If the queue contains at least one element, no lock
will be taken. If the queue is empty, the calling thread will sleep until an element is added from another thread, or
until `timeout_ms` milliseconds have passed. If the wait timed out, a value of NULL is returned, otherwise
`thread_queue_consume` returns the value that was removed from the queue. If the `timeout_ms` parameter is
THREAD_QUEUE_WAIT_INFINITE, `thread_queue_consume` waits indefinitely.
thread_queue_count
------------------
int thread_queue_count( thread_queue_t* queue )
Returns the number of elements currently held in a single-producer/single-consumer queue. Be aware that by the time you
get the count, it might have changed by another thread calling consume or produce, so use with care.
*/
/*
----------------------
IMPLEMENTATION
----------------------
*/
#ifndef thread_impl
#define thread_impl
union thread_mutex_t
{
void* align;
char data[ 64 ];
};
union thread_signal_t
{
void* align;
char data[ 116 ];
};
union thread_atomic_int_t
{
void* align;
long i;
};
union thread_atomic_ptr_t
{
void* ptr;
};
union thread_timer_t
{
void* data;
char d[ 8 ];
};
struct thread_queue_t
{
thread_signal_t data_ready;
thread_signal_t space_open;
thread_atomic_int_t count;
thread_atomic_int_t head;
thread_atomic_int_t tail;
void** values;
int size;
#ifndef NDEBUG
thread_atomic_int_t id_produce_is_set;
thread_id_t id_produce;
thread_atomic_int_t id_consume_is_set;
thread_id_t id_consume;
#endif
};
#endif /* thread_impl */
#ifdef THREAD_IMPLEMENTATION
#undef THREAD_IMPLEMENTATION
#ifndef THREAD_ASSERT
#undef _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#undef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <assert.h>
#define THREAD_ASSERT( expression, message ) assert( ( expression ) && ( message ) )
#endif
#if defined( _WIN32 )
#pragma comment( lib, "winmm.lib" )
#define _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#if !defined( _WIN32_WINNT ) || _WIN32_WINNT < 0x0501
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x501// requires Windows XP minimum
#endif
#define _WINSOCKAPI_
#pragma warning( push )
#pragma warning( disable: 4619 )
#pragma warning( disable: 4668 ) // 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives'
#pragma warning( disable: 4768 ) // __declspec attributes before linkage specification are ignored
#pragma warning( disable: 4255 ) // 'function' : no function prototype given: converting '()' to '(void)'
#include <windows.h>
#pragma warning( pop )
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <stdint.h>
#else
#error Unknown platform.
#endif
thread_id_t thread_current_thread_id( void )
{
#if defined( _WIN32 )
return (void*) (uintptr_t)GetCurrentThreadId();
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
return (void*) pthread_self();
#else
#error Unknown platform.
#endif
}
void thread_yield( void )
{
#if defined( _WIN32 )
SwitchToThread();
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
sched_yield();
#else
#error Unknown platform.
#endif
}
void thread_exit( int return_code )
{
#if defined( _WIN32 )
ExitThread( (DWORD) return_code );
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_exit( (void*)(uintptr_t) return_code );
#else
#error Unknown platform.
#endif
}
thread_ptr_t thread_create( int (*thread_proc)( void* ), void* user_data, int stack_size )
{
#if defined( _WIN32 )
DWORD thread_id;
HANDLE handle = CreateThread( NULL, stack_size > 0 ? (size_t)stack_size : 0U,
(LPTHREAD_START_ROUTINE)(uintptr_t) thread_proc, user_data, 0, &thread_id );
if( !handle ) return NULL;
return (thread_ptr_t) handle;
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_t thread;
if( 0 != pthread_create( &thread, NULL, ( void* (*)( void * ) ) thread_proc, user_data ) )
return NULL;
return (thread_ptr_t) thread;
#else
#error Unknown platform.
#endif
}
void thread_destroy( thread_ptr_t thread )
{
#if defined( _WIN32 )
WaitForSingleObject( (HANDLE) thread, INFINITE );
CloseHandle( (HANDLE) thread );
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_join( (pthread_t) thread, NULL );
#else
#error Unknown platform.
#endif
}
int thread_join( thread_ptr_t thread )
{
#if defined( _WIN32 )
WaitForSingleObject( (HANDLE) thread, INFINITE );
DWORD retval;
GetExitCodeThread( (HANDLE) thread, &retval );
return (int) retval;
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
void* retval;
pthread_join( (pthread_t) thread, &retval );
return (int)(uintptr_t) retval;
#else
#error Unknown platform.
#endif
}
int thread_detach( thread_ptr_t thread )
{
#if defined( _WIN32 )
return CloseHandle( (HANDLE) thread ) != 0;
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
return pthread_detach( (pthread_t) thread ) == 0;
#else
#error Unknown platform.
#endif
}
void thread_set_high_priority( void )
{
#if defined( _WIN32 )
SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_HIGHEST );
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
struct sched_param sp;
memset( &sp, 0, sizeof( sp ) );
sp.sched_priority = sched_get_priority_min( SCHED_RR );
pthread_setschedparam( pthread_self(), SCHED_RR, &sp);
#else
#error Unknown platform.
#endif
}
void thread_mutex_init( thread_mutex_t* mutex )
{
#if defined( _WIN32 )
// Compile-time size check
#pragma warning( push )
#pragma warning( disable: 4214 ) // nonstandard extension used: bit field types other than int
struct x { char thread_mutex_type_too_small : ( sizeof( thread_mutex_t ) < sizeof( CRITICAL_SECTION ) ? 0 : 1 ); };
#pragma warning( pop )
InitializeCriticalSectionAndSpinCount( (CRITICAL_SECTION*) mutex, 32 );
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
// Compile-time size check
struct x { char thread_mutex_type_too_small : ( sizeof( thread_mutex_t ) < sizeof( pthread_mutex_t ) ? 0 : 1 ); };
pthread_mutex_init( (pthread_mutex_t*) mutex, NULL );
#else
#error Unknown platform.
#endif
}
void thread_mutex_term( thread_mutex_t* mutex )
{
#if defined( _WIN32 )
DeleteCriticalSection( (CRITICAL_SECTION*) mutex );
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_mutex_destroy( (pthread_mutex_t*) mutex );
#else
#error Unknown platform.
#endif
}
void thread_mutex_lock( thread_mutex_t* mutex )
{
#if defined( _WIN32 )
EnterCriticalSection( (CRITICAL_SECTION*) mutex );
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_mutex_lock( (pthread_mutex_t*) mutex );
#else
#error Unknown platform.
#endif
}
void thread_mutex_unlock( thread_mutex_t* mutex )
{
#if defined( _WIN32 )
LeaveCriticalSection( (CRITICAL_SECTION*) mutex );
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_mutex_unlock( (pthread_mutex_t*) mutex );
#else
#error Unknown platform.
#endif
}
struct thread_internal_signal_t
{
#if defined( _WIN32 )
#if _WIN32_WINNT >= 0x0600
CRITICAL_SECTION mutex;
CONDITION_VARIABLE condition;
int value;
#else
#pragma message( "Warning: _WIN32_WINNT < 0x0600 - condition variables not available" )
HANDLE event;
#endif
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_mutex_t mutex;
pthread_cond_t condition;
int value;
#else
#error Unknown platform.
#endif
};
void thread_signal_init( thread_signal_t* signal )
{
// Compile-time size check
#pragma warning( push )
#pragma warning( disable: 4214 ) // nonstandard extension used: bit field types other than int
struct x { char thread_signal_type_too_small : ( sizeof( thread_signal_t ) < sizeof( struct thread_internal_signal_t ) ? 0 : 1 ); };
#pragma warning( pop )
struct thread_internal_signal_t* internal = (struct thread_internal_signal_t*) signal;
#if defined( _WIN32 )
#if _WIN32_WINNT >= 0x0600
InitializeCriticalSectionAndSpinCount( &internal->mutex, 32 );
InitializeConditionVariable( &internal->condition );
internal->value = 0;
#else
internal->event = CreateEvent( NULL, FALSE, FALSE, NULL );
#endif
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_mutex_init( &internal->mutex, NULL );
pthread_cond_init( &internal->condition, NULL );
internal->value = 0;
#else
#error Unknown platform.
#endif
}
void thread_signal_term( thread_signal_t* signal )
{
struct thread_internal_signal_t* internal = (struct thread_internal_signal_t*) signal;
#if defined( _WIN32 )
#if _WIN32_WINNT >= 0x0600
DeleteCriticalSection( &internal->mutex );
#else
CloseHandle( internal->event );
#endif
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_mutex_destroy( &internal->mutex );
pthread_cond_destroy( &internal->condition );
#else
#error Unknown platform.
#endif
}
void thread_signal_raise( thread_signal_t* signal )
{
struct thread_internal_signal_t* internal = (struct thread_internal_signal_t*) signal;
#if defined( _WIN32 )
#if _WIN32_WINNT >= 0x0600
EnterCriticalSection( &internal->mutex );
internal->value = 1;
LeaveCriticalSection( &internal->mutex );
WakeConditionVariable( &internal->condition );
#else
SetEvent( internal->event );
#endif
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
pthread_mutex_lock( &internal->mutex );
internal->value = 1;
pthread_mutex_unlock( &internal->mutex );
pthread_cond_signal( &internal->condition );
#else
#error Unknown platform.
#endif
}
int thread_signal_wait( thread_signal_t* signal, int timeout_ms )
{
struct thread_internal_signal_t* internal = (struct thread_internal_signal_t*) signal;
#if defined( _WIN32 )
#if _WIN32_WINNT >= 0x0600
int timed_out = 0;
EnterCriticalSection( &internal->mutex );
while( internal->value == 0 )
{
BOOL res = SleepConditionVariableCS( &internal->condition, &internal->mutex, timeout_ms < 0 ? INFINITE : timeout_ms );
if( !res && GetLastError() == ERROR_TIMEOUT ) { timed_out = 1; break; }
}
internal->value = 0;
LeaveCriticalSection( &internal->mutex );
return !timed_out;
#else
int failed = WAIT_OBJECT_0 != WaitForSingleObject( internal->event, timeout_ms < 0 ? INFINITE : timeout_ms );
return !failed;
#endif
#elif defined( __linux__ ) || defined( __APPLE__ ) || defined( __ANDROID__ )
struct timespec ts;
if( timeout_ms >= 0 )
{
struct timeval tv;
gettimeofday( &tv, NULL );
ts.tv_sec = time( NULL ) + timeout_ms / 1000;
ts.tv_nsec = tv.tv_usec * 1000 + 1000 * 1000 * ( timeout_ms % 1000 );
ts.tv_sec += ts.tv_nsec / ( 1000 * 1000 * 1000 );
ts.tv_nsec %= ( 1000 * 1000 * 1000 );
}
int timed_out = 0;
pthread_mutex_lock( &internal->mutex );
while( internal->value == 0 )
{
if( timeout_ms < 0 )