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
|
#if defined(GB_SYSTEM_LINUX)
#include <signal.h>
#if __has_include(<valgrind/helgrind.h>)
#include <valgrind/helgrind.h>
#define HAS_VALGRIND
#endif
#endif
#if defined(GB_SYSTEM_WINDOWS)
#pragma warning(push)
#pragma warning(disable: 4505)
#endif
#if defined(HAS_VALGRIND)
#define ANNOTATE_LOCK_PRE(m, t) VALGRIND_HG_MUTEX_LOCK_PRE(m, t)
#define ANNOTATE_LOCK_POST(m) VALGRIND_HG_MUTEX_LOCK_POST(m)
#define ANNOTATE_UNLOCK_PRE(m) VALGRIND_HG_MUTEX_UNLOCK_PRE(m)
#define ANNOTATE_UNLOCK_POST(m) VALGRIND_HG_MUTEX_UNLOCK_POST(m)
#define ANNOTATE_SEM_WAIT_POST(s) VALGRIND_HG_SEM_WAIT_POST(s)
#define ANNOTATE_SEM_POST_PRE(s) VALGRIND_HG_SEM_POST_PRE(s)
#else
#define ANNOTATE_LOCK_PRE(m, t)
#define ANNOTATE_LOCK_POST(m)
#define ANNOTATE_UNLOCK_PRE(m)
#define ANNOTATE_UNLOCK_POST(m)
#define ANNOTATE_SEM_WAIT_POST(s)
#define ANNOTATE_SEM_POST_PRE(s)
#endif
struct BlockingMutex;
struct RecursiveMutex;
struct RwMutex;
struct Semaphore;
struct Condition;
struct Thread;
struct ThreadPool;
struct Parker;
#define THREAD_PROC(name) isize name(struct Thread *thread)
gb_internal THREAD_PROC(thread_pool_thread_proc);
#define WORKER_TASK_PROC(name) isize name(void *data)
typedef WORKER_TASK_PROC(WorkerTaskProc);
typedef struct WorkerTask {
WorkerTaskProc *do_work;
void *data;
} WorkerTask;
struct Thread {
#if defined(GB_SYSTEM_WINDOWS)
void *win32_handle;
#else
pthread_t posix_handle;
#endif
isize idx;
WorkerTask *queue;
size_t capacity;
std::atomic<uint64_t> head_and_tail;
isize stack_size;
struct ThreadPool *pool;
};
typedef std::atomic<i32> Futex;
typedef volatile i32 Footex;
gb_internal void futex_wait(Futex *addr, Footex val);
gb_internal void futex_signal(Futex *addr);
gb_internal void futex_broadcast(Futex *addr);
gb_internal void mutex_lock (BlockingMutex *m);
gb_internal bool mutex_try_lock(BlockingMutex *m);
gb_internal void mutex_unlock (BlockingMutex *m);
gb_internal void mutex_lock (RecursiveMutex *m);
gb_internal bool mutex_try_lock(RecursiveMutex *m);
gb_internal void mutex_unlock (RecursiveMutex *m);
gb_internal void rw_mutex_lock (RwMutex *m);
gb_internal bool rw_mutex_try_lock (RwMutex *m);
gb_internal void rw_mutex_unlock (RwMutex *m);
gb_internal void rw_mutex_shared_lock (RwMutex *m);
gb_internal bool rw_mutex_try_shared_lock(RwMutex *m);
gb_internal void rw_mutex_shared_unlock (RwMutex *m);
gb_internal void semaphore_post(Semaphore *s, i32 count);
gb_internal void semaphore_wait(Semaphore *s);
gb_internal void condition_broadcast(Condition *c);
gb_internal void condition_signal(Condition *c);
gb_internal void condition_wait(Condition *c, BlockingMutex *m);
gb_internal void park(Parker *p);
gb_internal void unpark_one(Parker *p);
gb_internal void unpark_all(Parker *p);
gb_internal u32 thread_current_id(void);
gb_internal void thread_init (ThreadPool *pool, Thread *t, isize idx);
gb_internal void thread_init_and_start (ThreadPool *pool, Thread *t, isize idx);
gb_internal void thread_join_and_destroy(Thread *t);
gb_internal void thread_set_name (Thread *t, char const *name);
gb_internal void yield_thread(void);
gb_internal void yield_process(void);
struct Wait_Signal {
Futex futex;
};
gb_internal void wait_signal_until_available(Wait_Signal *ws) {
if (ws->futex.load() == 0) {
futex_wait(&ws->futex, 1);
}
}
gb_internal void wait_signal_set(Wait_Signal *ws) {
ws->futex.store(1);
futex_broadcast(&ws->futex);
}
struct MutexGuard {
MutexGuard() = delete;
MutexGuard(MutexGuard const &) = delete;
MutexGuard(MutexGuard &&) = delete;
explicit MutexGuard(BlockingMutex *bm) noexcept : bm{bm} {
mutex_lock(this->bm);
}
explicit MutexGuard(RecursiveMutex *rm) noexcept : rm{rm} {
mutex_lock(this->rm);
}
explicit MutexGuard(RwMutex *rwm) noexcept : rwm{rwm} {
rw_mutex_lock(this->rwm);
}
explicit MutexGuard(BlockingMutex &bm) noexcept : bm{&bm} {
mutex_lock(this->bm);
}
explicit MutexGuard(RecursiveMutex &rm) noexcept : rm{&rm} {
mutex_lock(this->rm);
}
explicit MutexGuard(RwMutex &rwm) noexcept : rwm{&rwm} {
rw_mutex_lock(this->rwm);
}
~MutexGuard() noexcept {
if (this->bm) {
mutex_unlock(this->bm);
} else if (this->rm) {
mutex_unlock(this->rm);
} else if (this->rwm) {
rw_mutex_unlock(this->rwm);
}
}
operator bool() const noexcept { return true; }
BlockingMutex *bm;
RecursiveMutex *rm;
RwMutex *rwm;
};
#define MUTEX_GUARD_BLOCK(m) if (MutexGuard GB_DEFER_3(_mutex_guard_){m})
#define MUTEX_GUARD(m) mutex_lock(m); defer (mutex_unlock(m))
#define RW_MUTEX_GUARD(m) rw_mutex_lock(m); defer (rw_mutex_unlock(m))
struct RecursiveMutex {
Futex owner;
i32 recursion;
};
gb_internal void mutex_lock(RecursiveMutex *m) {
Futex tid;
tid.store(cast(i32)thread_current_id());
for (;;) {
i32 prev_owner = 0;
m->owner.compare_exchange_strong(prev_owner, tid, std::memory_order_acquire, std::memory_order_acquire);
if (prev_owner == 0 || prev_owner == tid) {
m->recursion++;
// inside the lock
return;
}
futex_wait(&m->owner, prev_owner);
}
}
gb_internal bool mutex_try_lock(RecursiveMutex *m) {
Futex tid;
tid.store(cast(i32)thread_current_id());
i32 prev_owner = 0;
m->owner.compare_exchange_strong(prev_owner, tid, std::memory_order_acquire, std::memory_order_acquire);
if (prev_owner == 0 || prev_owner == tid) {
m->recursion++;
// inside the lock
return true;
}
return false;
}
gb_internal void mutex_unlock(RecursiveMutex *m) {
m->recursion--;
if (m->recursion != 0) {
return;
}
m->owner.exchange(0, std::memory_order_release);
futex_signal(&m->owner);
// outside the lock
}
struct Semaphore {
Footex count_;
Futex &count() noexcept {
return *(Futex *)&this->count_;
}
Futex const &count() const noexcept {
return *(Futex *)&this->count_;
}
};
gb_internal void semaphore_post(Semaphore *s, i32 count) {
s->count().fetch_add(count, std::memory_order_release);
if (s->count().load() == 1) {
futex_signal(&s->count());
} else {
futex_broadcast(&s->count());
}
}
gb_internal void semaphore_wait(Semaphore *s) {
for (;;) {
i32 original_count = s->count().load(std::memory_order_relaxed);
while (original_count == 0) {
futex_wait(&s->count(), original_count);
original_count = s->count().load(std::memory_order_relaxed);
}
if (s->count().compare_exchange_strong(original_count, original_count-1, std::memory_order_acquire, std::memory_order_acquire)) {
return;
}
}
}
#if defined(GB_SYSTEM_WINDOWS)
struct BlockingMutex {
SRWLOCK srwlock;
};
gb_internal void mutex_lock(BlockingMutex *m) {
AcquireSRWLockExclusive(&m->srwlock);
}
gb_internal bool mutex_try_lock(BlockingMutex *m) {
return !!TryAcquireSRWLockExclusive(&m->srwlock);
}
gb_internal void mutex_unlock(BlockingMutex *m) {
ReleaseSRWLockExclusive(&m->srwlock);
}
struct Condition {
CONDITION_VARIABLE cond;
};
gb_internal void condition_broadcast(Condition *c) {
WakeAllConditionVariable(&c->cond);
}
gb_internal void condition_signal(Condition *c) {
WakeConditionVariable(&c->cond);
}
gb_internal void condition_wait(Condition *c, BlockingMutex *m) {
SleepConditionVariableSRW(&c->cond, &m->srwlock, INFINITE, 0);
}
struct RwMutex {
SRWLOCK srwlock;
};
gb_internal void rw_mutex_lock(RwMutex *m) {
AcquireSRWLockExclusive(&m->srwlock);
}
gb_internal bool rw_mutex_try_lock(RwMutex *m) {
return !!TryAcquireSRWLockExclusive(&m->srwlock);
}
gb_internal void rw_mutex_unlock(RwMutex *m) {
ReleaseSRWLockExclusive(&m->srwlock);
}
gb_internal void rw_mutex_shared_lock(RwMutex *m) {
AcquireSRWLockShared(&m->srwlock);
}
gb_internal bool rw_mutex_try_shared_lock(RwMutex *m) {
return !!TryAcquireSRWLockShared(&m->srwlock);
}
gb_internal void rw_mutex_shared_unlock(RwMutex *m) {
ReleaseSRWLockShared(&m->srwlock);
}
#else
enum Internal_Mutex_State : i32 {
Internal_Mutex_State_Unlocked = 0,
Internal_Mutex_State_Locked = 1,
Internal_Mutex_State_Waiting = 2,
};
struct BlockingMutex {
#if defined(HAS_VALGRIND)
// BlockingMutex() {
// VALGRIND_HG_MUTEX_INIT_POST(this, 0);
// }
// ~BlockingMutex() {
// VALGRIND_HG_MUTEX_DESTROY_PRE(this);
// }
#endif
i32 state_;
Futex &state() {
return *(Futex *)&this->state_;
}
Futex const &state() const {
return *(Futex const *)&this->state_;
}
};
gb_no_inline gb_internal void mutex_lock_slow(BlockingMutex *m, i32 curr_state) {
i32 new_state = curr_state;
for (i32 spin = 0; spin < 100; spin++) {
i32 state = Internal_Mutex_State_Unlocked;
bool ok = m->state().compare_exchange_weak(state, new_state, std::memory_order_acquire, std::memory_order_consume);
if (ok) {
return;
}
if (state == Internal_Mutex_State_Waiting) {
break;
}
for (i32 i = gb_min(spin+1, 32); i > 0; i--) {
yield_thread();
}
}
// Set just in case 100 iterations did not do it
new_state = Internal_Mutex_State_Waiting;
for (;;) {
if (m->state().exchange(Internal_Mutex_State_Waiting, std::memory_order_acquire) == Internal_Mutex_State_Unlocked) {
return;
}
futex_wait(&m->state(), new_state);
yield_thread();
}
}
gb_internal void mutex_lock(BlockingMutex *m) {
ANNOTATE_LOCK_PRE(m, 0);
i32 v = m->state().exchange(Internal_Mutex_State_Locked, std::memory_order_acquire);
if (v != Internal_Mutex_State_Unlocked) {
mutex_lock_slow(m, v);
}
ANNOTATE_LOCK_POST(m);
}
gb_internal bool mutex_try_lock(BlockingMutex *m) {
ANNOTATE_LOCK_PRE(m, 1);
i32 v = m->state().exchange(Internal_Mutex_State_Locked, std::memory_order_acquire);
if (v == Internal_Mutex_State_Unlocked) {
ANNOTATE_LOCK_POST(m);
return true;
}
return false;
}
gb_no_inline gb_internal void mutex_unlock_slow(BlockingMutex *m) {
futex_signal(&m->state());
}
gb_internal void mutex_unlock(BlockingMutex *m) {
ANNOTATE_UNLOCK_PRE(m);
i32 v = m->state().exchange(Internal_Mutex_State_Unlocked, std::memory_order_release);
switch (v) {
case Internal_Mutex_State_Unlocked:
GB_PANIC("Unreachable");
break;
case Internal_Mutex_State_Locked:
// Okay
break;
case Internal_Mutex_State_Waiting:
mutex_unlock_slow(m);
break;
}
ANNOTATE_UNLOCK_POST(m);
}
struct Condition {
i32 state_;
Futex &state() {
return *(Futex *)&this->state_;
}
Futex const &state() const {
return *(Futex const *)&this->state_;
}
};
gb_internal void condition_broadcast(Condition *c) {
c->state().fetch_add(1, std::memory_order_release);
futex_broadcast(&c->state());
}
gb_internal void condition_signal(Condition *c) {
c->state().fetch_add(1, std::memory_order_release);
futex_signal(&c->state());
}
gb_internal void condition_wait(Condition *c, BlockingMutex *m) {
i32 state = c->state().load(std::memory_order_relaxed);
mutex_unlock(m);
futex_wait(&c->state(), state);
mutex_lock(m);
}
struct RwMutex {
// TODO(bill): make this a proper RW mutex
BlockingMutex mutex;
};
gb_internal void rw_mutex_lock(RwMutex *m) {
mutex_lock(&m->mutex);
}
gb_internal bool rw_mutex_try_lock(RwMutex *m) {
return mutex_try_lock(&m->mutex);
}
gb_internal void rw_mutex_unlock(RwMutex *m) {
mutex_unlock(&m->mutex);
}
gb_internal void rw_mutex_shared_lock(RwMutex *m) {
mutex_lock(&m->mutex);
}
gb_internal bool rw_mutex_try_shared_lock(RwMutex *m) {
return mutex_try_lock(&m->mutex);
}
gb_internal void rw_mutex_shared_unlock(RwMutex *m) {
mutex_unlock(&m->mutex);
}
#endif
struct Parker {
Futex state;
};
enum ParkerState : u32 {
ParkerState_Empty = 0,
ParkerState_Notified = 1,
ParkerState_Parked = UINT32_MAX,
};
gb_internal void park(Parker *p) {
if (p->state.fetch_sub(1, std::memory_order_acquire) == ParkerState_Notified) {
return;
}
for (;;) {
futex_wait(&p->state, ParkerState_Parked);
i32 notified = ParkerState_Empty;
if (p->state.compare_exchange_strong(notified, ParkerState_Empty, std::memory_order_acquire, std::memory_order_acquire)) {
return;
}
}
}
gb_internal void unpark_one(Parker *p) {
if (p->state.exchange(ParkerState_Notified, std::memory_order_release) == ParkerState_Parked) {
futex_signal(&p->state);
}
}
gb_internal void unpark_all(Parker *p) {
if (p->state.exchange(ParkerState_Notified, std::memory_order_release) == ParkerState_Parked) {
futex_broadcast(&p->state);
}
}
gb_internal u32 thread_current_id(void) {
u32 thread_id;
#if defined(GB_SYSTEM_WINDOWS)
#if defined(GB_ARCH_32_BIT) && defined(GB_CPU_X86)
thread_id = (cast(u32 *)__readfsdword(24))[9];
#elif defined(GB_ARCH_64_BIT) && defined(GB_CPU_X86)
thread_id = (cast(u32 *)__readgsqword(48))[18];
#else
thread_id = GetCurrentThreadId();
#endif
#elif defined(GB_SYSTEM_OSX) && defined(GB_ARCH_64_BIT)
thread_id = pthread_mach_thread_np(pthread_self());
#elif defined(GB_ARCH_32_BIT) && defined(GB_CPU_X86)
__asm__("mov %%gs:0x08,%0" : "=r"(thread_id));
#elif defined(GB_ARCH_64_BIT) && defined(GB_CPU_X86)
__asm__("mov %%fs:0x10,%0" : "=r"(thread_id));
#elif defined(GB_SYSTEM_LINUX)
thread_id = gettid();
#elif defined(GB_SYSTEM_HAIKU)
thread_id = find_thread(NULL);
#else
#error Unsupported architecture for thread_current_id()
#endif
return thread_id;
}
gb_internal gb_inline void yield_thread(void) {
#if defined(GB_SYSTEM_WINDOWS)
_mm_pause();
#elif defined(GB_SYSTEM_OSX)
#if defined(GB_CPU_X86)
__asm__ volatile ("" : : : "memory");
#elif defined(GB_CPU_ARM)
__asm__ volatile ("yield" : : : "memory");
#endif
#elif defined(GB_CPU_X86)
_mm_pause();
#elif defined(GB_CPU_ARM)
__asm__ volatile ("yield" : : : "memory");
#else
#error Unknown architecture
#endif
}
gb_internal gb_inline void yield(void) {
#if defined(GB_SYSTEM_WINDOWS)
YieldProcessor();
#else
sched_yield();
#endif
}
#if defined(GB_SYSTEM_WINDOWS)
gb_internal DWORD __stdcall internal_thread_proc(void *arg) {
Thread *t = cast(Thread *)arg;
thread_pool_thread_proc(t);
return 0;
}
#else
gb_internal void *internal_thread_proc(void *arg) {
#if (GB_SYSTEM_LINUX)
// NOTE: Don't permit any signal delivery to threads on Linux.
sigset_t mask = {};
sigfillset(&mask);
GB_ASSERT_MSG(pthread_sigmask(SIG_BLOCK, &mask, nullptr) == 0, "failed to block signals");
#endif
Thread *t = cast(Thread *)arg;
thread_pool_thread_proc(t);
return NULL;
}
#endif
gb_internal void thread_init(ThreadPool *pool, Thread *t, isize idx) {
gb_zero_item(t);
#if defined(GB_SYSTEM_WINDOWS)
t->win32_handle = INVALID_HANDLE_VALUE;
#else
t->posix_handle = 0;
#endif
t->capacity = 1 << 14; // must be a power of 2
t->queue = gb_alloc_array(heap_allocator(), WorkerTask, t->capacity);
t->head_and_tail = 0;
t->pool = pool;
t->idx = idx;
}
gb_internal void thread_init_and_start(ThreadPool *pool, Thread *t, isize idx) {
thread_init(pool, t, idx);
isize stack_size = 0;
#if defined(GB_SYSTEM_WINDOWS)
t->win32_handle = CreateThread(NULL, stack_size, internal_thread_proc, t, 0, NULL);
GB_ASSERT_MSG(t->win32_handle != NULL, "CreateThread: GetLastError");
#else
{
pthread_attr_t attr;
pthread_attr_init(&attr);
defer (pthread_attr_destroy(&attr));
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
if (stack_size != 0) {
pthread_attr_setstacksize(&attr, stack_size);
}
pthread_create(&t->posix_handle, &attr, internal_thread_proc, t);
}
#endif
}
gb_internal void thread_join_and_destroy(Thread *t) {
#if defined(GB_SYSTEM_WINDOWS)
WaitForSingleObject(t->win32_handle, INFINITE);
CloseHandle(t->win32_handle);
t->win32_handle = INVALID_HANDLE_VALUE;
#else
pthread_join(t->posix_handle, NULL);
t->posix_handle = 0;
#endif
gb_free(heap_allocator(), t->queue);
}
gb_internal void thread_set_name(Thread *t, char const *name) {
#if defined(GB_COMPILER_MSVC)
#pragma pack(push, 8)
typedef struct {
DWORD type;
char const *name;
DWORD id;
DWORD flags;
} gbprivThreadName;
#pragma pack(pop)
gbprivThreadName tn;
tn.type = 0x1000;
tn.name = name;
tn.id = GetThreadId(cast(HANDLE)t->win32_handle);
tn.flags = 0;
__try {
RaiseException(0x406d1388, 0, gb_size_of(tn)/4, cast(ULONG_PTR *)&tn);
} __except(1 /*EXCEPTION_EXECUTE_HANDLER*/) {
}
#elif defined(GB_SYSTEM_WINDOWS) && !defined(GB_COMPILER_MSVC)
// IMPORTANT TODO(bill): Set thread name for GCC/Clang on windows
return;
#elif defined(GB_SYSTEM_OSX)
// TODO(bill): Test if this works
pthread_setname_np(name);
#elif defined(GB_SYSTEM_FREEBSD) || defined(GB_SYSTEM_OPENBSD)
pthread_set_name_np(t->posix_handle, name);
#else
// TODO(bill): Test if this works
pthread_setname_np(t->posix_handle, name);
#endif
}
#if defined(GB_SYSTEM_LINUX)
#include <linux/futex.h>
#include <sys/syscall.h>
gb_internal void futex_signal(Futex *addr) {
int ret = syscall(SYS_futex, addr, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1, NULL, NULL, 0);
if (ret == -1) {
perror("Futex wake");
GB_PANIC("Failed in futex wake!\n");
}
}
gb_internal void futex_broadcast(Futex *addr) {
int ret = syscall(SYS_futex, addr, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, INT32_MAX, NULL, NULL, 0);
if (ret == -1) {
perror("Futex wake");
GB_PANIC("Failed in futex wake!\n");
}
}
gb_internal void futex_wait(Futex *addr, Footex val) {
for (;;) {
int ret = syscall(SYS_futex, addr, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, val, NULL, NULL, 0);
if (ret == -1) {
if (errno != EAGAIN) {
perror("Futex wait");
GB_PANIC("Failed in futex wait!\n");
} else {
return;
}
} else if (ret == 0) {
if (*addr != val) {
return;
}
}
}
}
#elif defined(GB_SYSTEM_FREEBSD)
#include <sys/types.h>
#include <sys/umtx.h>
gb_internal void futex_signal(Futex *addr) {
_umtx_op(addr, UMTX_OP_WAKE, 1, 0, 0);
}
gb_internal void futex_broadcast(Futex *addr) {
_umtx_op(addr, UMTX_OP_WAKE, INT32_MAX, 0, 0);
}
gb_internal void futex_wait(Futex *addr, Footex val) {
for (;;) {
int ret = _umtx_op(addr, UMTX_OP_WAIT_UINT, val, 0, NULL);
if (ret == -1) {
if (errno == ETIMEDOUT || errno == EINTR) {
continue;
}
perror("Futex wait");
GB_PANIC("Failed in futex wait!\n");
} else if (ret == 0) {
if (*addr != val) {
return;
}
}
}
}
#elif defined(GB_SYSTEM_OPENBSD)
#include <sys/futex.h>
gb_internal void futex_signal(Futex *f) {
for (;;) {
int ret = futex((volatile uint32_t *)f, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1, NULL, NULL);
if (ret == -1) {
if (errno == ETIMEDOUT || errno == EINTR) {
continue;
}
perror("Futex wake");
GB_PANIC("futex wake fail");
} else if (ret == 1) {
return;
}
}
}
gb_internal void futex_broadcast(Futex *f) {
for (;;) {
int ret = futex((volatile uint32_t *)f, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, INT32_MAX, NULL, NULL);
if (ret == -1) {
if (errno == ETIMEDOUT || errno == EINTR) {
continue;
}
perror("Futex wake");
GB_PANIC("futex wake fail");
} else if (ret == 1) {
return;
}
}
}
gb_internal void futex_wait(Futex *f, Footex val) {
for (;;) {
int ret = futex((volatile uint32_t *)f, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, val, NULL, NULL);
if (ret == -1) {
if (*f != val) {
return;
}
if (errno == ETIMEDOUT || errno == EINTR) {
continue;
}
perror("Futex wait");
GB_PANIC("Failed in futex wait!\n");
}
}
}
#elif defined(GB_SYSTEM_OSX)
#define UL_COMPARE_AND_WAIT 0x00000001
#define ULF_NO_ERRNO 0x01000000
extern "C" int __ulock_wait(uint32_t operation, void *addr, uint64_t value, uint32_t timeout); /* timeout is specified in microseconds */
extern "C" int __ulock_wake(uint32_t operation, void *addr, uint64_t wake_value);
gb_internal void futex_signal(Futex *f) {
for (;;) {
int ret = __ulock_wake(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO, f, 0);
if (ret >= 0) {
return;
}
if (ret == -EINTR || ret == -EFAULT) {
continue;
}
if (ret == -ENOENT) {
return;
}
GB_PANIC("Failed in futex wake!\n");
}
}
gb_internal void futex_broadcast(Futex *f) {
for (;;) {
enum { ULF_WAKE_ALL = 0x00000100 };
int ret = __ulock_wake(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO | ULF_WAKE_ALL, f, 0);
if (ret == 0) {
return;
}
if (ret == -EINTR || ret == -EFAULT) {
continue;
}
if (ret == -ENOENT) {
return;
}
GB_PANIC("Failed in futex wake!\n");
}
}
gb_internal void futex_wait(Futex *f, Footex val) {
for (;;) {
int ret = __ulock_wait(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO, f, val, 0);
if (ret >= 0) {
if (*f != val) {
return;
}
continue;
}
if (ret == -EINTR || ret == -EFAULT) {continue;
ret = -ret;
}
if (ret == -ENOENT) {
return;
}
GB_PANIC("Failed in futex wait!\n");
}
}
#elif defined(GB_SYSTEM_WINDOWS)
gb_internal void futex_signal(Futex *f) {
WakeByAddressSingle(f);
}
gb_internal void futex_broadcast(Futex *f) {
WakeByAddressAll(f);
}
gb_internal void futex_wait(Futex *f, Footex val) {
do {
WaitOnAddress(f, (void *)&val, sizeof(val), INFINITE);
} while (f->load() == val);
}
#elif defined(GB_SYSTEM_HAIKU)
// Futex implementation taken from https://tavianator.com/2023/futex.html
#include <pthread.h>
#include <atomic>
struct Futex_Wait_Node {
pthread_t thread;
Futex *futex;
Futex_Wait_Node *prev, *next;
};
struct Futex_Wait_Queue {
std::atomic_flag spinlock;
Futex_Wait_Node list;
void lock() {
while (spinlock.test_and_set(std::memory_order_acquire)) {
; // spin...
}
}
void unlock() {
spinlock.clear(std::memory_order_release);
}
};
// FIXME: This approach may scale badly in the future,
// possible solution - hash map (leads to deadlocks now).
Futex_Wait_Queue g_waitq = {
.spinlock = ATOMIC_FLAG_INIT,
.list = {
.prev = &g_waitq.list,
.next = &g_waitq.list,
},
};
Futex_Wait_Queue *get_wait_queue(Futex *f) {
// Future hash map method...
return &g_waitq;
}
void futex_signal(Futex *f) {
auto waitq = get_wait_queue(f);
waitq->lock();
auto head = &waitq->list;
for (auto waiter = head->next; waiter != head; waiter = waiter->next) {
if (waiter->futex == f) {
pthread_kill(waiter->thread, SIGCONT);
break;
}
}
waitq->unlock();
}
void futex_broadcast(Futex *f) {
auto waitq = get_wait_queue(f);
waitq->lock();
auto head = &waitq->list;
for (auto waiter = head->next; waiter != head; waiter = waiter->next) {
if (waiter->futex == f) {
pthread_kill(waiter->thread, SIGCONT);
}
}
waitq->unlock();
}
void futex_wait(Futex *f, Footex val) {
auto waitq = get_wait_queue(f);
waitq->lock();
auto head = &waitq->list;
Futex_Wait_Node waiter;
waiter.thread = pthread_self();
waiter.futex = f;
waiter.prev = head;
waiter.next = head->next;
waiter.prev->next = &waiter;
waiter.next->prev = &waiter;
sigset_t old_mask, mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCONT);
pthread_sigmask(SIG_BLOCK, &mask, &old_mask);
if (*f == val) {
waitq->unlock();
int sig;
sigwait(&mask, &sig);
waitq->lock();
}
waiter.prev->next = waiter.next;
waiter.next->prev = waiter.prev;
pthread_sigmask(SIG_SETMASK, &old_mask, NULL);
waitq->unlock();
}
#endif
#if defined(GB_SYSTEM_WINDOWS)
#pragma warning(pop)
#endif
|