-
Notifications
You must be signed in to change notification settings - Fork 189
Expand file tree
/
Copy paththread.c
More file actions
1112 lines (1015 loc) · 28.2 KB
/
thread.c
File metadata and controls
1112 lines (1015 loc) · 28.2 KB
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 (C)2005-2016 Haxe Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <hl.h>
#include "hlsystem.h"
typedef struct _hl_semaphore hl_semaphore;
typedef struct _hl_condition hl_condition;
#if !defined(HL_THREADS)
struct _hl_mutex {
void (*free)( hl_mutex * );
void *_unused;
};
struct _hl_semaphore {
void (*free)(hl_semaphore *);
};
struct _hl_condition {
void (*free)(hl_condition *);
};
struct _hl_tls {
void (*free)( hl_tls * );
void *value;
};
#elif defined(HL_WIN)
struct _hl_mutex {
void (*free)( hl_mutex * );
CRITICAL_SECTION cs;
bool is_gc;
};
struct _hl_semaphore {
void (*free)(hl_semaphore *);
HANDLE sem;
};
struct _hl_condition {
void (*free)(hl_condition *);
CRITICAL_SECTION cs;
CONDITION_VARIABLE cond;
};
#else
# include <pthread.h>
# include <unistd.h>
# include <sys/syscall.h>
# include <sys/time.h>
#ifdef __APPLE__
#include <dispatch/dispatch.h>
#else
#include <semaphore.h>
#endif
struct _hl_mutex {
void (*free)( hl_mutex * );
pthread_mutex_t lock;
bool is_gc;
};
struct _hl_semaphore {
void (*free)(hl_semaphore *);
# ifdef __APPLE__
dispatch_semaphore_t sem;
# else
sem_t sem;
#endif
};
struct _hl_condition {
void (*free)(hl_condition *);
pthread_mutex_t mutex;
pthread_cond_t cond;
};
#endif
// ----------------- ALLOC
HL_PRIM hl_mutex *hl_mutex_alloc( bool gc_thread ) {
# if !defined(HL_THREADS)
static struct _hl_mutex null_mutex = {0};
return (hl_mutex*)&null_mutex;
# elif defined(HL_WIN)
hl_mutex *l = (hl_mutex*)hl_gc_alloc_finalizer(sizeof(hl_mutex));
l->free = hl_mutex_free;
l->is_gc = gc_thread;
InitializeCriticalSection(&l->cs);
return l;
# else
hl_mutex *l = (hl_mutex*)hl_gc_alloc_finalizer(sizeof(hl_mutex));
l->free = hl_mutex_free;
l->is_gc = gc_thread;
pthread_mutexattr_t a;
pthread_mutexattr_init(&a);
pthread_mutexattr_settype(&a,PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&l->lock,&a);
pthread_mutexattr_destroy(&a);
return l;
# endif
}
HL_PRIM void hl_mutex_acquire( hl_mutex *l ) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
if( l->is_gc ) hl_blocking(true);
EnterCriticalSection(&l->cs);
if( l->is_gc ) hl_blocking(false);
# else
if( l->is_gc ) hl_blocking(true);
pthread_mutex_lock(&l->lock);
if( l->is_gc ) hl_blocking(false);
# endif
}
HL_PRIM bool hl_mutex_try_acquire( hl_mutex *l ) {
#if !defined(HL_THREADS)
return true;
# elif defined(HL_WIN)
return (bool)TryEnterCriticalSection(&l->cs);
# else
return pthread_mutex_trylock(&l->lock) == 0;
# endif
}
HL_PRIM void hl_mutex_release( hl_mutex *l ) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
LeaveCriticalSection(&l->cs);
# else
pthread_mutex_unlock(&l->lock);
# endif
}
HL_PRIM void hl_mutex_free( hl_mutex *l ) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
if( l->free ) {
DeleteCriticalSection(&l->cs);
l->free = NULL;
}
# else
if( l->free ) {
pthread_mutex_destroy(&l->lock);
l->free = NULL;
}
# endif
}
#define _MUTEX _ABSTRACT(hl_mutex)
DEFINE_PRIM(_MUTEX, mutex_alloc, _BOOL);
DEFINE_PRIM(_VOID, mutex_acquire, _MUTEX);
DEFINE_PRIM(_BOOL, mutex_try_acquire, _MUTEX);
DEFINE_PRIM(_VOID, mutex_release, _MUTEX);
DEFINE_PRIM(_VOID, mutex_free, _MUTEX);
// ------------------ SEMAPHORE
HL_PRIM hl_semaphore *hl_semaphore_alloc(int value) {
# if !defined(HL_THREADS)
static struct _hl_semaphore null_semaphore = {0};
return (hl_semaphore *)&null_semaphore;
# elif defined(HL_WIN)
hl_semaphore *sem =
(hl_semaphore *)hl_gc_alloc_finalizer(sizeof(hl_semaphore));
sem->free = hl_semaphore_free;
sem->sem = CreateSemaphoreW(NULL, value, 0x7FFFFFFF, NULL);
return sem;
# else
hl_semaphore *sem =
(hl_semaphore *)hl_gc_alloc_finalizer(sizeof(hl_semaphore));
sem->free = hl_semaphore_free;
# ifdef __APPLE__
sem->sem = dispatch_semaphore_create(value);
# else
sem_init(&sem->sem, false, value);
# endif
return sem;
# endif
}
HL_PRIM void hl_semaphore_acquire(hl_semaphore *sem) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
hl_blocking(true);
WaitForSingleObject(sem->sem, INFINITE);
hl_blocking(false);
# else
# ifdef __APPLE__
hl_blocking(true);
dispatch_semaphore_wait(sem->sem, DISPATCH_TIME_FOREVER);
hl_blocking(false);
# else
hl_blocking(true);
sem_wait(&sem->sem);
hl_blocking(false);
# endif
# endif
}
HL_PRIM bool hl_semaphore_try_acquire(hl_semaphore *sem, vdynamic *timeout) {
# if !defined(HL_THREADS)
return true;
# elif defined(HL_WIN)
hl_blocking(true);
bool ret = WaitForSingleObject(sem->sem,
timeout ? (DWORD)((FLOAT)timeout->v.d * 1000.0)
: 0) == WAIT_OBJECT_0;
hl_blocking(false);
return ret;
# else
# ifdef __APPLE__
hl_blocking(true);
bool ret = dispatch_semaphore_wait(
sem->sem, dispatch_time(DISPATCH_TIME_NOW,
(int64_t)((timeout ? timeout->v.d : 0) *
1000 * 1000 * 1000))) == 0;
hl_blocking(false);
return ret;
# else
hl_blocking(true);
bool ret;
if (timeout) {
struct timeval tv;
struct timespec t;
double delta = timeout->v.d;
int idelta = (int)delta, idelta2;
delta -= idelta;
delta *= 1.0e9;
gettimeofday(&tv, NULL);
delta += tv.tv_usec * 1000.0;
idelta2 = (int)(delta / 1e9);
delta -= idelta2 * 1e9;
t.tv_sec = tv.tv_sec + idelta + idelta2;
t.tv_nsec = (long)delta;
ret = sem_timedwait(&sem->sem, &t) == 0;
} else {
ret = sem_trywait(&sem->sem) == 0;
}
hl_blocking(false);
return ret;
# endif
# endif
}
HL_PRIM void hl_semaphore_release(hl_semaphore *sem) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
ReleaseSemaphore(sem->sem, 1, NULL);
# else
# ifdef __APPLE__
dispatch_semaphore_signal(sem->sem);
# else
sem_post(&sem->sem);
# endif
# endif
}
HL_PRIM void hl_semaphore_free(hl_semaphore *sem) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
if (sem->free) {
CloseHandle(sem->sem);
sem->free = NULL;
}
# else
if (sem->free) {
#ifndef __APPLE__
sem_destroy(&sem->sem);
#endif
sem->free = NULL;
}
# endif
}
#define _SEMAPHORE _ABSTRACT(hl_semaphore)
DEFINE_PRIM(_SEMAPHORE, semaphore_alloc, _I32);
DEFINE_PRIM(_VOID, semaphore_acquire, _SEMAPHORE);
DEFINE_PRIM(_BOOL, semaphore_try_acquire, _SEMAPHORE _NULL(_F64));
DEFINE_PRIM(_VOID, semaphore_release, _SEMAPHORE);
DEFINE_PRIM(_VOID, semaphore_free, _SEMAPHORE);
// ------------------ CONDITION
HL_PRIM hl_condition *hl_condition_alloc() {
# if !defined(HL_THREADS)
static struct _hl_condition null_condition = {0};
return (hl_condition *)&null_condition;
# elif defined(HL_WIN)
hl_condition *cond =
(hl_condition *)hl_gc_alloc_finalizer(sizeof(hl_condition));
cond->free = hl_condition_free;
InitializeCriticalSection(&cond->cs);
InitializeConditionVariable(&cond->cond);
return cond;
# else
hl_condition *cond =
(hl_condition *)hl_gc_alloc_finalizer(sizeof(hl_condition));
cond->free = hl_condition_free;
pthread_condattr_t attr;
pthread_condattr_init(&attr);
pthread_cond_init(&cond->cond, &attr);
pthread_condattr_destroy(&attr);
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&cond->mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
return cond;
# endif
}
HL_PRIM void hl_condition_acquire(hl_condition *cond) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
hl_blocking(true);
EnterCriticalSection(&cond->cs);
hl_blocking(false);
# else
hl_blocking(true);
pthread_mutex_lock(&cond->mutex);
hl_blocking(false);
# endif
}
HL_PRIM bool hl_condition_try_acquire(hl_condition *cond) {
# if !defined(HL_THREADS)
return true;
# elif defined(HL_WIN)
return (bool)TryEnterCriticalSection(&cond->cs);
# else
return pthread_mutex_trylock(&cond->mutex) == 0;
# endif
}
HL_PRIM void hl_condition_release(hl_condition *cond) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
LeaveCriticalSection(&cond->cs);
# else
pthread_mutex_unlock(&cond->mutex);
# endif
}
HL_PRIM void hl_condition_wait(hl_condition *cond) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
hl_blocking(true);
SleepConditionVariableCS(&cond->cond, &cond->cs, INFINITE);
hl_blocking(false);
# else
hl_blocking(true);
pthread_cond_wait(&cond->cond, &cond->mutex);
hl_blocking(false);
# endif
}
HL_PRIM bool hl_condition_timed_wait(hl_condition *cond, double timeout) {
# if !defined(HL_THREADS)
return true;
# elif defined(HL_WIN)
hl_blocking(true);
SleepConditionVariableCS(&cond->cond, &cond->cs,
(DWORD)((FLOAT)timeout * 1000.0));
hl_blocking(false);
return true;
# else
struct timeval tv;
struct timespec t;
double delta = timeout;
int idelta = (int)delta, idelta2;
delta -= idelta;
delta *= 1.0e9;
gettimeofday(&tv, NULL);
delta += tv.tv_usec * 1000.0;
idelta2 = (int)(delta / 1e9);
delta -= idelta2 * 1e9;
t.tv_sec = tv.tv_sec + idelta + idelta2;
t.tv_nsec = (long)delta;
hl_blocking(true);
bool ret = pthread_cond_timedwait(&cond->cond, &cond->mutex, &t) == 0;
hl_blocking(false);
return ret;
# endif
}
HL_PRIM void hl_condition_signal(hl_condition *cond) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
WakeConditionVariable(&cond->cond);
# else
pthread_cond_signal(&cond->cond);
# endif
}
HL_PRIM void hl_condition_broadcast(hl_condition *cond) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
WakeAllConditionVariable(&cond->cond);
# else
pthread_cond_broadcast(&cond->cond);
# endif
}
HL_PRIM void hl_condition_free(hl_condition *cond) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
if (cond->free) {
DeleteCriticalSection(&cond->cs);
cond->free = NULL;
}
# else
if (cond->free) {
pthread_cond_destroy(&cond->cond);
pthread_mutex_destroy(&cond->mutex);
cond->free = NULL;
}
# endif
}
#define _CONDITION _ABSTRACT(hl_condition)
DEFINE_PRIM(_CONDITION, condition_alloc, _NO_ARG)
DEFINE_PRIM(_VOID, condition_acquire, _CONDITION)
DEFINE_PRIM(_BOOL, condition_try_acquire, _CONDITION)
DEFINE_PRIM(_VOID, condition_release, _CONDITION)
DEFINE_PRIM(_VOID, condition_wait, _CONDITION)
DEFINE_PRIM(_BOOL, condition_timed_wait, _CONDITION _F64)
DEFINE_PRIM(_VOID, condition_signal, _CONDITION)
DEFINE_PRIM(_VOID, condition_broadcast, _CONDITION)
// ----------------- THREAD LOCAL
int get_tls_slot();
void free_tls_slot(int id);
struct _hl_tls {
void (*free)( hl_tls * );
int key;
bool gc;
};
static void tls_free(hl_tls *l) { free_tls_slot(l->key); }
HL_PRIM hl_tls *hl_tls_alloc( bool gc_value ) {
hl_tls *l = (hl_tls*)hl_gc_alloc_finalizer(sizeof(hl_tls));
l->free = tls_free;
l->gc = gc_value;
l->key = get_tls_slot();
return l;
}
HL_PRIM void hl_tls_set( hl_tls *l, void *v ) {
hl_thread_info *info = hl_get_thread();
if (l->key >= info->tls_arr_size) {
int new_max = info->tls_arr_size > 0 ? info->tls_arr_size * 2 : 16;
new_max = l->key > new_max ? l->key : new_max;
void **new_arr = hl_gc_alloc_raw(sizeof(void*) * new_max);
memcpy(new_arr, info->tls_arr, info->tls_arr_size * sizeof(void*));
info->tls_arr = new_arr;
info->tls_arr_size = new_max;
}
info->tls_arr[l->key] = v;
}
HL_PRIM void *hl_tls_get( hl_tls *l ) {
hl_thread_info *info = hl_get_thread();
if (l->key < info->tls_arr_size) {
return info->tls_arr[l->key];
} else {
return NULL;
}
}
#define _TLS _ABSTRACT(hl_tls)
DEFINE_PRIM(_TLS, tls_alloc, _BOOL);
DEFINE_PRIM(_DYN, tls_get, _TLS);
DEFINE_PRIM(_VOID, tls_set, _TLS _DYN);
// ----------------- DEQUE
typedef struct _tqueue {
vdynamic *msg;
struct _tqueue *next;
} tqueue;
struct _hl_deque;
typedef struct _hl_deque hl_deque;
struct _hl_deque {
void (*free)( hl_deque * );
tqueue *first;
tqueue *last;
#ifdef HL_THREADS
# ifdef HL_WIN
CRITICAL_SECTION lock;
HANDLE wait;
# else
pthread_mutex_t lock;
pthread_cond_t wait;
# endif
#endif
};
#if !defined(HL_THREADS)
# define LOCK(l)
# define UNLOCK(l)
# define SIGNAL(l)
#elif defined(HL_WIN)
# define LOCK(l) EnterCriticalSection(&(l))
# define UNLOCK(l) LeaveCriticalSection(&(l))
# define SIGNAL(l) ReleaseSemaphore(l,1,NULL)
#else
# define LOCK(l) pthread_mutex_lock(&(l))
# define UNLOCK(l) pthread_mutex_unlock(&(l))
# define SIGNAL(l) pthread_cond_signal(&(l))
#endif
static void hl_deque_free( hl_deque *q ) {
hl_remove_root(&q->first);
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
DeleteCriticalSection(&q->lock);
CloseHandle(q->wait);
# else
pthread_mutex_destroy(&q->lock);
pthread_cond_destroy(&q->wait);
# endif
}
HL_PRIM hl_deque *hl_deque_alloc() {
hl_deque *q = (hl_deque*)hl_gc_alloc_finalizer(sizeof(hl_deque));
q->free = hl_deque_free;
q->first = NULL;
q->last = NULL;
hl_add_root(&q->first);
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
q->wait = CreateSemaphore(NULL,0,(1 << 30),NULL);
InitializeCriticalSection(&q->lock);
# else
pthread_mutex_init(&q->lock,NULL);
pthread_cond_init(&q->wait,NULL);
# endif
return q;
}
HL_PRIM void hl_deque_add( hl_deque *q, vdynamic *msg ) {
tqueue *t = (tqueue*)hl_gc_alloc_raw(sizeof(tqueue));
t->msg = msg;
t->next = NULL;
LOCK(q->lock);
if( q->last == NULL )
q->first = t;
else
q->last->next = t;
q->last = t;
SIGNAL(q->wait);
UNLOCK(q->lock);
}
HL_PRIM void hl_deque_push( hl_deque *q, vdynamic *msg ) {
tqueue *t = (tqueue*)hl_gc_alloc_raw(sizeof(tqueue));
t->msg = msg;
LOCK(q->lock);
t->next = q->first;
q->first = t;
if( q->last == NULL )
q->last = t;
SIGNAL(q->wait);
UNLOCK(q->lock);
}
HL_PRIM vdynamic *hl_deque_pop( hl_deque *q, bool block ) {
vdynamic *msg;
hl_blocking(true);
LOCK(q->lock);
while( q->first == NULL )
if( block ) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
UNLOCK(q->lock);
WaitForSingleObject(q->wait,INFINITE);
LOCK(q->lock);
# else
pthread_cond_wait(&q->wait,&q->lock);
# endif
} else {
UNLOCK(q->lock);
hl_blocking(false);
return NULL;
}
msg = q->first->msg;
q->first = q->first->next;
if( q->first == NULL )
q->last = NULL;
else
SIGNAL(q->wait);
UNLOCK(q->lock);
hl_blocking(false);
return msg;
}
#define _DEQUE _ABSTRACT(hl_deque)
DEFINE_PRIM(_DEQUE, deque_alloc, _NO_ARG);
DEFINE_PRIM(_VOID, deque_add, _DEQUE _DYN);
DEFINE_PRIM(_VOID, deque_push, _DEQUE _DYN);
DEFINE_PRIM(_DYN, deque_pop, _DEQUE _BOOL);
// ----------------- LOCK
struct _hl_lock;
typedef struct _hl_lock hl_lock;
struct _hl_lock {
void (*free)( hl_lock * );
#if !defined(HL_THREADS)
int counter;
#elif defined(HL_WIN)
HANDLE wait;
#else
pthread_mutex_t lock;
pthread_cond_t wait;
int counter;
#endif
};
static void hl_lock_free( hl_lock *l ) {
# if !defined(HL_THREADS)
# elif defined(HL_WIN)
CloseHandle(l->wait);
# else
pthread_mutex_destroy(&l->lock);
pthread_cond_destroy(&l->wait);
# endif
}
HL_PRIM hl_lock *hl_lock_create() {
hl_lock *l = (hl_lock*)hl_gc_alloc_finalizer(sizeof(hl_lock));
l->free = hl_lock_free;
# if !defined(HL_THREADS)
l->counter = 0;
# elif defined(HL_WIN)
l->wait = CreateSemaphore(NULL,0,(1 << 30),NULL);
# else
l->counter = 0;
pthread_mutex_init(&l->lock,NULL);
pthread_cond_init(&l->wait,NULL);
# endif
return l;
}
HL_PRIM void hl_lock_release( hl_lock *l ) {
# if !defined(HL_THREADS)
l->counter++;
# elif defined(HL_WIN)
ReleaseSemaphore(l->wait,1,NULL);
# else
pthread_mutex_lock(&l->lock);
l->counter++;
pthread_cond_signal(&l->wait);
pthread_mutex_unlock(&l->lock);
# endif
}
HL_PRIM bool hl_lock_wait( hl_lock *l, vdynamic *timeout ) {
# if !defined(HL_THREADS)
if( l->counter == 0 ) return false;
l->counter--;
return true;
# elif defined(HL_WIN)
DWORD ret;
hl_blocking(true);
ret = WaitForSingleObject(l->wait, timeout?(DWORD)((FLOAT)timeout->v.d * 1000.0):INFINITE);
hl_blocking(false);
switch( ret ) {
case WAIT_ABANDONED:
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
return false;
default:
hl_error("Lock wait error");
}
# else
{
hl_blocking(true);
pthread_mutex_lock(&l->lock);
while( l->counter == 0 ) {
if( timeout ) {
struct timeval tv;
struct timespec t;
double delta = timeout->v.d;
int idelta = (int)delta, idelta2;
delta -= idelta;
delta *= 1.0e9;
gettimeofday(&tv,NULL);
delta += tv.tv_usec * 1000.0;
idelta2 = (int)(delta / 1e9);
delta -= idelta2 * 1e9;
t.tv_sec = tv.tv_sec + idelta + idelta2;
t.tv_nsec = (long)delta;
if( pthread_cond_timedwait(&l->wait,&l->lock,&t) != 0 ) {
pthread_mutex_unlock(&l->lock);
hl_blocking(false);
return false;
}
} else
pthread_cond_wait(&l->wait,&l->lock);
}
l->counter--;
if( l->counter > 0 )
pthread_cond_signal(&l->wait);
pthread_mutex_unlock(&l->lock);
hl_blocking(false);
return true;
}
# endif
}
#define _LOCK _ABSTRACT(hl_lock)
DEFINE_PRIM(_LOCK, lock_create, _NO_ARG);
DEFINE_PRIM(_VOID, lock_release, _LOCK);
DEFINE_PRIM(_BOOL, lock_wait, _LOCK _NULL(_F64));
// ----------------- THREAD
HL_PRIM hl_thread *hl_thread_current() {
#if !defined(HL_THREADS)
return NULL;
#elif defined(HL_WIN)
return (hl_thread*)(int_val)GetCurrentThreadId();
#else
return (hl_thread*)pthread_self();
#endif
}
HL_PRIM void hl_thread_yield() {
#if !defined(Hl_THREADS)
// nothing
#elif defined(HL_WIN)
Sleep(0);
#else
pthread_yield();
#endif
}
HL_PRIM int hl_thread_id() {
#if !defined(HL_THREADS)
return 0;
#elif defined(HL_WIN)
return (int)GetCurrentThreadId();
#elif defined(HL_MAC)
uint64_t tid64;
pthread_threadid_np(NULL, &tid64);
return (pid_t)tid64;
#elif defined(SYS_gettid) && !defined(HL_TVOS)
return syscall(SYS_gettid);
#else
return -1;
#endif
}
typedef struct {
void (*callb)( void *);
void *param;
hl_lock *wait;
} thread_start;
#ifdef HL_THREADS
static void gc_thread_entry( thread_start *_s ) {
thread_start s = *_s;
hl_register_thread(&s);
hl_lock_release(_s->wait);
s.wait = _s->wait = NULL;
_s = NULL;
s.callb(s.param);
hl_unregister_thread();
}
#endif
HL_PRIM hl_thread *hl_thread_start( void *callback, void *param, bool withGC ) {
#ifdef HL_THREADS
if( withGC ) {
thread_start *s = (thread_start*)hl_gc_alloc_raw(sizeof(thread_start));
s->callb = callback;
s->param = param;
s->wait = hl_lock_create();
callback = gc_thread_entry;
param = s;
}
#endif
#if !defined(HL_THREADS)
hl_error("Threads support is disabled");
return NULL;
#elif defined(HL_WIN)
DWORD tid;
HANDLE h = CreateThread(NULL,0,callback,param,0,&tid);
if( h == NULL )
return NULL;
CloseHandle(h);
if( withGC ) {
hl_lock *l = ((thread_start*)param)->wait;
if( l ) hl_lock_wait(l, NULL);
}
return (hl_thread*)(int_val)tid;
#else
pthread_t t;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
if( pthread_create(&t,&attr,callback,param) != 0 ) {
pthread_attr_destroy(&attr);
return NULL;
}
pthread_attr_destroy(&attr);
if( withGC ) {
hl_lock *l = ((thread_start*)param)->wait;
if( l ) hl_lock_wait(l, NULL);
}
return (hl_thread*)t;
#endif
}
static void hl_run_thread( vclosure *c ) {
bool isExc;
vdynamic *exc = hl_dyn_call_safe(c,NULL,0,&isExc);
if( !isExc )
return;
hl_print_uncaught_exception(exc);
}
HL_PRIM hl_thread *hl_thread_create( vclosure *c ) {
return hl_thread_start(hl_run_thread,c,true);
}
#if defined(HL_WIN) && defined(HL_THREADS)
#ifdef HL_MINGW
static void SetThreadName(DWORD dwThreadID, const char* threadName) {
SetThreadDescription(
OpenThread(THREAD_SET_LIMITED_INFORMATION, FALSE, dwThreadID),
hl_to_utf16(threadName)
);
}
#else
const DWORD MS_VC_EXCEPTION = 0x406D1388;
#pragma pack(push,8)
typedef struct tagTHREADNAME_INFO
{
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
#pragma pack(pop)
void SetThreadName(DWORD dwThreadID, const char* threadName) {
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = threadName;
info.dwThreadID = dwThreadID;
info.dwFlags = 0;
#pragma warning(push)
#pragma warning(disable: 6320 6322)
__try{
RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
}
__except (EXCEPTION_EXECUTE_HANDLER){
}
#pragma warning(pop)
}
#endif
#endif
HL_PRIM int hl_get_thread_id( hl_thread *t ) {
# if !defined(HL_THREADS)
return 0;
#elif defined(HL_WIN)
return (DWORD)(int_val)t;
#elif defined(HL_MAC)
uint64_t tid64;
pthread_threadid_np((pthread_t)t, &tid64);
return (pid_t)tid64;
#else
return -1; // no way to get that on linux :'(
#endif
}
HL_PRIM void hl_thread_set_name( hl_thread *t, const char *name ) {
#if !defined(HL_THREADS)
// nothing
#elif defined(HL_WIN)
SetThreadName((DWORD)(int_val)t,name);
#elif defined(HL_MAC) || defined(HL_IOS)
// pthread_setname_np only possible for current thread
#else
pthread_setname_np((pthread_t)t,name);
#endif
#ifdef HL_THREADS
hl_threads_info *threads = hl_gc_threads_info();
hl_thread_info *tinf;
int tid = hl_get_thread_id(t);
int len = (int)strlen(name);
if( len >= 127 ) len = 126;
for(int i=0;i<threads->count;i++) {
tinf = threads->threads[i];
if( tinf->thread_id == tid ) {
memcpy(tinf->thread_name, name, len);
tinf->thread_name[len + 1] = 0;
}
}
#endif
}
HL_PRIM vbyte *hl_thread_get_name( hl_thread *t ) {
#ifdef HL_THREADS
hl_threads_info *threads = hl_gc_threads_info();
hl_thread_info *tinf;
int tid = hl_get_thread_id(t);
for(int i=0;i<threads->count;i++) {
tinf = threads->threads[i];
if( tinf->thread_id == tid )
return *tinf->thread_name ? (vbyte*)tinf->thread_name : NULL;
}
#endif
return NULL;
}
#define _THREAD _ABSTRACT(hl_thread)
DEFINE_PRIM(_THREAD, thread_current, _NO_ARG);
DEFINE_PRIM(_THREAD, thread_create, _FUN(_VOID,_NO_ARG));
DEFINE_PRIM(_VOID, thread_set_name, _THREAD _BYTES);
DEFINE_PRIM(_BYTES, thread_get_name, _THREAD);
// ----------------- ATOMICS
// Assumptions made:
// Everyone uses GCC, Clang or MSVC
// People are not using 8 year old versions of GCC.
#if defined(HL_GCC) || defined(HL_CLANG)
#define HL_GCC_ATOMICS
#elif defined(HL_VCC)
#define HL_VCC_ATOMICS
#include <intrin.h>
#else // Nearly everyone uses GCC, Clang or MSVC, right?
#error \
"Neither GCC, clang or MSVC is being used. Please contribute the relevant atomic instrinsics for your compiler."
#endif
HL_PRIM int hl_atomic_add32(int *a, int b) {
#if defined(HL_GCC_ATOMICS)
return __atomic_fetch_add(a, b, __ATOMIC_SEQ_CST);
#elif defined(HL_VCC_ATOMICS)
return _InterlockedExchangeAdd((long volatile *)a, b);
#endif
}
HL_PRIM int hl_atomic_sub32(int *a, int b) {
#if defined(HL_GCC_ATOMICS)
return __atomic_fetch_sub(a, b, __ATOMIC_SEQ_CST);
#elif defined(HL_VCC_ATOMICS)
return _InterlockedExchangeAdd((long volatile *)a, -b);
#endif
}
HL_PRIM int hl_atomic_and32(int *a, int b) {
#if defined(HL_GCC_ATOMICS)
return __atomic_fetch_and(a, b, __ATOMIC_SEQ_CST);
#elif defined(HL_VCC_ATOMICS)
return _InterlockedAnd((long volatile *)a, b);
#endif
}
HL_PRIM int hl_atomic_or32(int *a, int b) {
#if defined(HL_GCC_ATOMICS)
return __atomic_fetch_or(a, b, __ATOMIC_SEQ_CST);
#elif defined(HL_VCC_ATOMICS)
return _InterlockedOr((long volatile *)a, b);
#endif