-
Notifications
You must be signed in to change notification settings - Fork 268
/
cute_sync.h
1337 lines (1107 loc) · 34.3 KB
/
cute_sync.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.
------------------------------------------------------------------------------
cute_sync.h - v1.01
To create implementation (the function definitions)
#define CUTE_SYNC_IMPLEMENTATION
#define CUTE_SYNC_WINDOWS
in *one* C/CPP file (translation unit) that includes this file
SUMMARY
Collection of practical syncronization primitives for Windows/Posix/SDL2.
Here is a list of all supported primitives.
* atomic integer/pointer
* thread
* mutex
* condition variable
* semaphore
* read/write lock
* thread pool
Here are some slides I wrote for those interested in learning prequisite
knowledge for utilizing this header:
http://www.randygaul.net/2014/09/24/multi-threading-best-practices-for-gamedev/
A good chunk of this code came from Mattias Gustavsson's thread.h header.
It really is quite a good header, and worth considering!
https://github.com/mattiasgustavsson/libs
PLATFORMS
The current supported platforms are Windows/Posix/SDL. Here are the macros for
picking each implementation.
* CUTE_SYNC_WINDOWS
* CUTE_SYNC_POSIX
* CUTE_SYNC_SDL
REVISION HISTORY
1.0 (05/31/2018) initial release
1.01 (08/25/2019) Windows and pthreads port
*/
#if !defined(CUTE_SYNC_H)
typedef union cute_atomic_int_t cute_atomic_int_t;
typedef union cute_mutex_t cute_mutex_t;
typedef union cute_cv_t cute_cv_t;
typedef struct cute_semaphore_t cute_semaphore_t;
typedef struct cute_thread_t cute_thread_t;
typedef unsigned long long cute_thread_id_t;
typedef int (cute_thread_fn)(void *udata);
/**
* Creates an unlocked mutex.
*/
cute_mutex_t cute_mutex_create();
/**
* Returns 1 on success, zero otherwise.
*/
int cute_lock(cute_mutex_t* mutex);
/**
* Returns 1 on success, zero otherwise.
*/
int cute_unlock(cute_mutex_t* mutex);
/**
* Attempts to lock the mutex without blocking. Returns one if lock was acquired,
* otherwise returns zero.
*/
int cute_trylock(cute_mutex_t* mutex);
void cute_mutex_destroy(cute_mutex_t* mutex);
/**
* Constructs a condition variable, used to sleep or wake threads.
*/
cute_cv_t cute_cv_create();
/**
* Signals all sleeping threads to wake that are waiting on the condition variable.
* Returns 1 on success, zero otherwise.
*/
int cute_cv_wake_all(cute_cv_t* cv);
/**
* Signals a single thread to wake that are waiting on the condition variable.
* Returns 1 on success, zero otherwise.
*/
int cute_cv_wake_one(cute_cv_t* cv);
/**
* Places a thread to wait on the condition variable.
* Returns 1 on success, zero otherwise.
*/
int cute_cv_wait(cute_cv_t* cv, cute_mutex_t* mutex);
void cute_cv_destroy(cute_cv_t* cv);
/**
* Creates a semaphore with an initial internal value of `initial_count`.
* Returns NULL on failure.
*/
cute_semaphore_t cute_semaphore_create(int initial_count);
/**
* Automically increments the semaphore's value and then wakes a sleeping thread.
* Returns 1 on success, zero otherwise.
*/
int cute_semaphore_post(cute_semaphore_t* semaphore);
/**
* Non-blocking version of `cute_semaphore_wait`.
* Returns 1 on success, zero otherwise.
*/
int cute_semaphore_try(cute_semaphore_t* semaphore);
/**
* Suspends the calling thread's execution unless the semaphore's value is positive. Will
* decrement the value atomically afterwards.
* Returns 1 on success, zero otherwise.
*/
int cute_semaphore_wait(cute_semaphore_t* semaphore);
int cute_semaphore_value(cute_semaphore_t* semaphore);
void cute_semaphore_destroy(cute_semaphore_t* semaphore);
cute_thread_t* cute_thread_create(cute_thread_fn func, const char* name, void* udata);
/**
* An optimization, meaning the thread will never have `cute_thread_wait` called on it.
* Useful for certain long-lived threads.
* It is invalid to call `cute_thread_wait` on a detached thread.
* It is invalid to call `cute_thread_wait` on a thread more than once.
* Please see this link for a longer description: https://wiki.libsdl.org/SDL_DetachThread
*/
void cute_thread_detach(cute_thread_t* thread);
cute_thread_id_t cute_thread_get_id(cute_thread_t* thread);
cute_thread_id_t cute_thread_id();
/**
* Waits until the thread exits (unless it has already exited), and returns the thread's
* return code. Unless the thread was detached, this function must be used, otherwise it
* is considered a leak to leave an thread hanging around (even if it finished execution
* and returned).
*/
int cute_thread_wait(cute_thread_t* thread);
/**
* Returns the number of CPU cores on the machine. Can be affected my machine dependent technology,
* such as Intel's hyperthreading.
*/
int cute_core_count();
/**
* Returns the size of CPU's L1's cache line size in bytes.
*/
int cute_cacheline_size();
/**
* Returns the size of the machine's RAM in megabytes.
*/
int cute_ram_size();
/**
* Atomically adds `addend` at `atomic` and returns the old value at `atomic`.
*/
int cute_atomic_add(cute_atomic_int_t* atomic, int addend);
/**
* Atomically sets `value` at `atomic` and returns the old value at `atomic`.
*/
int cute_atomic_set(cute_atomic_int_t* atomic, int value);
/**
* Atomically fetches the value at `atomic`.
*/
int cute_atomic_get(cute_atomic_int_t* atomic);
/**
* Atomically sets `atomic` to `value` if `expected` equals `atomic`.
* Returns 1 of the value was set, 0 otherwise.
*/
int cute_atomic_cas(cute_atomic_int_t* atomic, int expected, int value);
/**
* Atomically sets `value` at `atomic` and returns the old value at `atomic`.
*/
void* cute_atomic_ptr_set(void** atomic, void* value);
/**
* Atomically fetches the value at `atomic`.
*/
void* cute_atomic_ptr_get(void** atomic);
/**
* Atomically sets `atomic` to `value` if `expected` equals `atomic`.
* Returns 1 of the value was set, 0 otherwise.
*/
int cute_atomic_ptr_cas(void** atomic, void* expected, void* value);
/**
* A reader/writer mutual exclusion lock. Allows many simultaneous readers or a single writer.
*
* The number of readers is capped by `CUTE_RW_LOCK_MAX_READERS` (or in other words, a nearly indefinite
* number). Exceeding `CUTE_RW_LOCK_MAX_READERS` simultaneous readers results in undefined behavior.
*/
typedef struct cute_rw_lock_t cute_rw_lock_t;
#define CUTE_RW_LOCK_MAX_READERS (1 << 30)
/**
* Constructs an unlocked mutual exclusion read/write lock. The `rw` lock can safely sit
* on the stack.
*/
cute_rw_lock_t cute_rw_lock_create();
/**
* Locks for reading. Many simultaneous readers are allowed.
*/
void cute_read_lock(cute_rw_lock_t* rw);
/**
* Undoes a single call to `cute_read_lock`.
*/
void cute_read_unlock(cute_rw_lock_t* rw);
/**
* Locks for writing. When locked for writing, only one writer can be present, and no readers.
*
* Will wait for active readers to call `cute_read_unlock`, or for active writers to call
* `cute_write_unlock`.
*/
void cute_write_lock(cute_rw_lock_t* rw);
/**
* Undoes a single call to `cute_write_lock`.
*/
void cute_write_unlock(cute_rw_lock_t* rw);
/**
* Destroys the internal semaphores, and mutex.
*/
void cute_rw_lock_destroy(cute_rw_lock_t* rw);
typedef struct cute_threadpool_t cute_threadpool_t;
/**
* Constructs a threadpool containing `thread_count`, useful for implementing job/task systems.
* `mem_ctx` can be NULL, and is used for custom allocation purposes.
*
* Returns NULL on error. Will return NULL if `CUTE_SYNC_CACHELINE_SIZE` is less than the actual
* cache line size on a given machine. `CUTE_SYNC_CACHELINE_SIZE` defaults to 128 bytes, and can
* be overidden by defining CUTE_SYNC_CACHELINE_SIZE before including cute_sync.h
*
* Makes a modest attempt at memory aligning to avoid false sharing, as an optimization.
*/
cute_threadpool_t* cute_threadpool_create(int thread_count, void* mem_ctx);
/**
* Atomically adds a single task to the internal task stack (FIFO order). The task is represented
* as a function pointer `func`, which does work. The `param` is passed to the `func` when the
* task is started.
*/
void cute_threadpool_add_task(cute_threadpool_t* pool, void (*func)(void*), void* param);
/**
* Wakes internal threads to perform tasks, and waits for all tasks to complete before returning.
* The calling thread will help perform available tasks while waiting.
*/
void cute_threadpool_kick_and_wait(cute_threadpool_t* pool);
/**
* Wakes internal threads to perform tasks and immediately returns.
*/
void cute_threadpool_kick(cute_threadpool_t* pool);
/**
* Cleans up all resources created from `cute_threadpool_create`.
*/
void cute_threadpool_destroy(cute_threadpool_t* pool);
#define CUTE_SYNC_H
#endif
//--------------------------------------------------------------------------------------------------
#ifndef CUTE_SYNC_TYPE_DEFINITIONS_H
union cute_atomic_int_t { void* align; long i; };
union cute_mutex_t { void* align; char data[64]; };
union cute_cv_t { void* align; char data[64]; };
struct cute_semaphore_t { void* id; cute_atomic_int_t count; };
struct cute_rw_lock_t
{
cute_mutex_t mutex;
cute_semaphore_t write_sem;
cute_semaphore_t read_sem;
cute_atomic_int_t readers;
cute_atomic_int_t readers_departing;
};
#define CUTE_SYNC_TYPE_DEFINITIONS_H
#endif
//--------------------------------------------------------------------------------------------------
#if defined(CUTE_SYNC_IMPLEMENTATION)
#if !defined(CUTE_SYNC_IMPLEMENTATION_ONCE)
#define CUTE_SYNC_IMPLEMENTATION_ONCE
#if defined(CUTE_SYNC_SDL)
#elif defined(CUTE_SYNC_WINDOWS)
#define WIN32_LEAN_AND_MEAN
// To use GetThreadId and other methods we must require Windows Vista minimum.
#if _WIN32_WINNT < 0x0600
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // requires Windows Vista minimum
// 0x0400=Windows NT 4.0, 0x0500=Windows 2000, 0x0501=Windows XP, 0x0502=Windows Server 2003, 0x0600=Windows Vista,
// 0x0601=Windows 7, 0x0602=Windows 8, 0x0603=Windows 8.1, 0x0A00=Windows 10
#endif
#include <Windows.h>
#elif defined(CUTE_SYNC_POSIX)
#include <pthread.h>
#include <semaphore.h>
// Just platforms with unistd.h are supported for now.
// So no FreeBSD, OS/2, or other weird platforms.
#include <unistd.h> // sysconf
#if defined(__APPLE__)
#include <sys/sysctl.h> // sysctlbyname
#endif
#else
#error Please choose a base implementation between CUTE_SYNC_SDL, CUTE_SYNC_WINDOWS and CUTE_SYNC_POSIX.
#endif
#if !defined(CUTE_SYNC_ALLOC)
#include <stdlib.h>
#define CUTE_SYNC_ALLOC(size, ctx) malloc(size)
#define CUTE_SYNC_FREE(ptr, ctx) free(ptr)
#endif
#if !defined(CUTE_SYNC_MEMCPY)
#include <string.h>
#define CUTE_SYNC_MEMCPY memcpy
#endif
#if !defined(CUTE_SYNC_YIELD)
#ifdef CUTE_SYNC_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h> // winnt
#define CUTE_SYNC_YIELD YieldProcessor
#elif defined(CUTE_SYNC_POSIX)
#include <sched.h>
#define CUTE_SYNC_YIELD sched_yield
#else
#define CUTE_SYNC_YIELD() // Not implemented by SDL.
#endif
#endif
#if !defined(CUTE_SYNC_ASSERT)
#include <assert.h>
#define CUTE_SYNC_ASSERT assert
#endif
#if !defined(CUTE_SYNC_CACHELINE_SIZE)
// Sized generously to try and avoid guessing "too low". Too small would incur serious overhead
// inside of `cute_threadpool_t` as false sharing would run amok between pooled threads.
#define CUTE_SYNC_CACHELINE_SIZE 128
#endif
// Atomics implementation.
// Use SDL2's implementation if available, otherwise WIN32 and GCC-like compilers are supported out-of-the-box.
#ifdef CUTE_SYNC_SDL
int cute_atomic_add(cute_atomic_int_t* atomic, int addend)
{
return SDL_AtomicAdd((SDL_atomic_t*)atomic, addend);
}
int cute_atomic_set(cute_atomic_int_t* atomic, int value)
{
return SDL_AtomicSet((SDL_atomic_t*)atomic, value);
}
int cute_atomic_get(cute_atomic_int_t* atomic)
{
return SDL_AtomicGet((SDL_atomic_t*)atomic);
}
int cute_atomic_cas(cute_atomic_int_t* atomic, int expected, int value)
{
return SDL_AtomicCAS((SDL_atomic_t*)atomic, expected, value);
}
void* cute_atomic_ptr_set(void** atomic, void* value)
{
return SDL_AtomicSetPtr(atomic, value);
}
void* cute_atomic_ptr_get(void** atomic)
{
return SDL_AtomicGetPtr(atomic);
}
int cute_atomic_ptr_cas(void** atomic, void* expected, void* value)
{
return SDL_AtomicCASPtr(atomic, expected, value);
}
#elif defined(CUTE_SYNC_WINDOWS)
int cute_atomic_add(cute_atomic_int_t* atomic, int addend)
{
return (int)_InterlockedExchangeAdd(&atomic->i, (LONG)addend);
}
int cute_atomic_set(cute_atomic_int_t* atomic, int value)
{
return (int)_InterlockedExchange(&atomic->i, value);
}
int cute_atomic_get(cute_atomic_int_t* atomic)
{
return (int)_InterlockedCompareExchange(&atomic->i, 0, 0);
}
int cute_atomic_cas(cute_atomic_int_t* atomic, int expected, int value)
{
return (int)_InterlockedCompareExchange(&atomic->i, value, expected) == value;
}
void* cute_atomic_ptr_set(void** atomic, void* value)
{
return _InterlockedExchangePointer(atomic, value);
}
void* cute_atomic_ptr_get(void** atomic)
{
return _InterlockedCompareExchangePointer(atomic, NULL, NULL);
}
int cute_atomic_ptr_cas(void** atomic, void* expected, void* value)
{
return _InterlockedCompareExchangePointer(atomic, value, expected) == value;
}
#elif defined(CUTE_SYNC_POSIX)
#if !(defined(__linux__) || defined(__APPLE__) || defined(__ANDROID__))
# error Unsupported platform found - no atomics implementation available for this compiler.
# error The section only implements GCC atomics.
#endif
int cute_atomic_add(cute_atomic_int_t* atomic, int addend)
{
return (int)__sync_fetch_and_add(&atomic->i, addend);
}
int cute_atomic_set(cute_atomic_int_t* atomic, int value)
{
int result = (int)__sync_lock_test_and_set(&atomic->i, value);
__sync_lock_release(&atomic->i);
return result;
}
int cute_atomic_get(cute_atomic_int_t* atomic)
{
return (int)__sync_fetch_and_add(&atomic->i, 0);
}
int cute_atomic_cas(cute_atomic_int_t* atomic, int expected, int value)
{
return (int)__sync_val_compare_and_swap(&atomic->i, expected, value) == value;
}
void* cute_atomic_ptr_set(void** atomic, void* value)
{
void* result = __sync_lock_test_and_set(atomic, value);
__sync_lock_release(atomic);
return result;
}
void* cute_atomic_ptr_get(void** atomic)
{
return __sync_fetch_and_add(atomic, NULL);
}
int cute_atomic_ptr_cas(void** atomic, void* expected, void* value)
{
return __sync_val_compare_and_swap(atomic, expected, value) == value;
}
#endif // End atomics implementation.
#if defined(CUTE_SYNC_SDL)
cute_mutex_t cute_mutex_create()
{
cute_mutex_t mutex;
mutex.align = SDL_CreateMutex();
return mutex;
}
int cute_lock(cute_mutex_t* mutex)
{
return !SDL_LockMutex((SDL_mutex*)mutex->align);
}
int cute_unlock(cute_mutex_t* mutex)
{
return !SDL_UnlockMutex((SDL_mutex*)mutex->align);
}
int cute_trylock(cute_mutex_t* mutex)
{
return !SDL_TryLockMutex((SDL_mutex*)mutex->align);
}
void cute_mutex_destroy(cute_mutex_t* mutex)
{
SDL_DestroyMutex((SDL_mutex*)mutex->align);
}
cute_cv_t cute_cv_create()
{
cute_cv_t cv;
cv.align = SDL_CreateCond();
return cv;
}
int cute_cv_wake_all(cute_cv_t* cv)
{
return !SDL_CondBroadcast((SDL_cond*)cv->align);
}
int cute_cv_wake_one(cute_cv_t* cv)
{
return !SDL_CondSignal((SDL_cond*)cv->align);
}
int cute_cv_wait(cute_cv_t* cv, cute_mutex_t* mutex)
{
return !SDL_CondWait((SDL_cond*)cv, (SDL_mutex*)mutex->align);
}
void cute_cv_destroy(cute_cv_t* cv)
{
SDL_DestroyCond((SDL_cond*)cv->align);
}
cute_semaphore_t cute_semaphore_create(int initial_count)
{
cute_semaphore_t semaphore;
semaphore.id = SDL_CreateSemaphore(initial_count);
semaphore.count.i = initial_count;
return semaphore;
}
int cute_semaphore_post(cute_semaphore_t* semaphore)
{
return !SDL_SemPost((SDL_sem*)semaphore->id);
}
int cute_semaphore_try(cute_semaphore_t* semaphore)
{
return !SDL_SemTryWait((SDL_sem*)semaphore->id);
}
int cute_semaphore_wait(cute_semaphore_t* semaphore)
{
return !SDL_SemWait((SDL_sem*)semaphore->id);
}
int cute_semaphore_value(cute_semaphore_t* semaphore)
{
return SDL_SemValue((SDL_sem*)semaphore->id);
}
void cute_semaphore_destroy(cute_semaphore_t* semaphore)
{
SDL_DestroySemaphore((SDL_sem*)semaphore->id);
}
cute_thread_t* cute_thread_create(cute_thread_fn func, const char* name, void* udata)
{
return (cute_thread_t*)SDL_CreateThread(func, name, udata);
}
void cute_thread_detach(cute_thread_t* thread)
{
SDL_DetachThread((SDL_Thread*)thread);
}
cute_thread_id_t cute_thread_get_id(cute_thread_t* thread)
{
return SDL_GetThreadID((SDL_Thread*)thread);
}
cute_thread_id_t cute_thread_id()
{
return SDL_ThreadID();
}
int cute_thread_wait(cute_thread_t* thread)
{
int ret;
SDL_WaitThread((SDL_Thread*)thread, &ret);
return ret;
}
int cute_core_count()
{
return SDL_GetCPUCount();
}
int cute_cacheline_size()
{
return SDL_GetCPUCacheLineSize();
}
int cute_ram_size()
{
return SDL_GetSystemRAM();
}
#elif defined(CUTE_SYNC_WINDOWS)
cute_mutex_t cute_mutex_create()
{
CUTE_SYNC_ASSERT(sizeof(CRITICAL_SECTION) <= sizeof(cute_mutex_t));
cute_mutex_t mutex;
InitializeCriticalSectionAndSpinCount((CRITICAL_SECTION*)&mutex, 2000);
return mutex;
}
int cute_lock(cute_mutex_t* mutex)
{
EnterCriticalSection((CRITICAL_SECTION*)mutex);
return 1;
}
int cute_unlock(cute_mutex_t* mutex)
{
LeaveCriticalSection((CRITICAL_SECTION*)mutex);
return 1;
}
int cute_trylock(cute_mutex_t* mutex)
{
return !TryEnterCriticalSection((CRITICAL_SECTION*)mutex);
}
void cute_mutex_destroy(cute_mutex_t* mutex)
{
DeleteCriticalSection((CRITICAL_SECTION*)mutex);
}
cute_cv_t cute_cv_create()
{
CUTE_SYNC_ASSERT(sizeof(CONDITION_VARIABLE) <= sizeof(cute_cv_t));
cute_cv_t cv;
InitializeConditionVariable((CONDITION_VARIABLE*)&cv);
return cv;
}
int cute_cv_wake_all(cute_cv_t* cv)
{
WakeAllConditionVariable((CONDITION_VARIABLE*)cv);
return 1;
}
int cute_cv_wake_one(cute_cv_t* cv)
{
WakeConditionVariable((CONDITION_VARIABLE*)cv);
return 1;
}
int cute_cv_wait(cute_cv_t* cv, cute_mutex_t* mutex)
{
return !!SleepConditionVariableCS((CONDITION_VARIABLE*)cv, (CRITICAL_SECTION*)mutex, INFINITE);
}
void cute_cv_destroy(cute_cv_t* cv)
{
// Nothing needed here on Windows... Weird!
// https://stackoverflow.com/questions/28975958/why-does-windows-have-no-deleteconditionvariable-function-to-go-together-with
}
cute_semaphore_t cute_semaphore_create(int initial_count)
{
cute_semaphore_t semaphore;
semaphore.id = CreateSemaphoreA(NULL, (LONG)initial_count, LONG_MAX, NULL);
semaphore.count.i = initial_count;
return semaphore;
}
int cute_semaphore_post(cute_semaphore_t* semaphore)
{
_InterlockedIncrement(&semaphore->count.i);
if (ReleaseSemaphore(semaphore->id, 1, NULL) == FALSE) {
_InterlockedDecrement(&semaphore->count.i);
return 0;
} else {
return 1;
}
}
static int s_wait(cute_semaphore_t* semaphore, DWORD milliseconds)
{
if (WaitForSingleObjectEx(semaphore->id, milliseconds, FALSE) == WAIT_OBJECT_0) {
return 1;
} else {
return 0;
}
}
int cute_semaphore_try(cute_semaphore_t* semaphore)
{
return s_wait(semaphore, 0);
}
int cute_semaphore_wait(cute_semaphore_t* semaphore)
{
return s_wait(semaphore, INFINITE);
}
int cute_semaphore_value(cute_semaphore_t* semaphore)
{
return cute_atomic_get(&semaphore->count);
}
void cute_semaphore_destroy(cute_semaphore_t* semaphore)
{
CloseHandle((HANDLE)semaphore->id);
}
cute_thread_t* cute_thread_create(cute_thread_fn fn, const char* name, void* udata)
{
(void)name;
DWORD unused;
HANDLE id = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)fn, udata, 0, &unused);
return (cute_thread_t*)id;
}
void cute_thread_detach(cute_thread_t* thread)
{
CloseHandle((HANDLE)thread);
}
cute_thread_id_t cute_thread_get_id(cute_thread_t* thread)
{
return GetThreadId((HANDLE)thread);
}
cute_thread_id_t cute_thread_id()
{
return GetCurrentThreadId();
}
int cute_thread_wait(cute_thread_t* thread)
{
WaitForSingleObject((HANDLE)thread, INFINITE);
CloseHandle((HANDLE)thread);
return 1;
}
int cute_core_count()
{
SYSTEM_INFO info;
GetSystemInfo(&info);
return (int)info.dwNumberOfProcessors;
}
int cute_cacheline_size()
{
DWORD buffer_size;
SYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer[256];
GetLogicalProcessorInformation(0, &buffer_size);
DWORD buffer_count = buffer_size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
if (buffer_count > 256) {
// Just guess... Since this machine has more than 256 cores?
// Supporting more than 256 cores would probably require a malloc here.
return 128;
}
GetLogicalProcessorInformation(buffer, &buffer_size);
for (DWORD i = 0; i < buffer_count; ++i) {
if (buffer[i].Relationship == RelationCache && buffer[i].Cache.Level == 1) {
return (int)buffer[i].Cache.LineSize;
}
}
// Just guess...
return 128;
}
int cute_ram_size()
{
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
return (int)(status.ullTotalPhys / (1024 * 1024));
}
#elif defined(CUTE_SYNC_POSIX)
cute_mutex_t cute_mutex_create()
{
CUTE_SYNC_ASSERT(sizeof(pthread_mutex_t) <= sizeof(cute_mutex_t));
cute_mutex_t mutex;
pthread_mutex_init((pthread_mutex_t*)&mutex, NULL);
return mutex;
}
int cute_lock(cute_mutex_t* mutex)
{
pthread_mutex_lock((pthread_mutex_t*)mutex);
return 1;
}
int cute_unlock(cute_mutex_t* mutex)
{
pthread_mutex_unlock((pthread_mutex_t*)mutex);
return 1;
}
int cute_trylock(cute_mutex_t* mutex)
{
return !pthread_mutex_trylock((pthread_mutex_t*)mutex);
}
void cute_mutex_destroy(cute_mutex_t* mutex)
{
pthread_mutex_destroy((pthread_mutex_t*)mutex);
}
cute_cv_t cute_cv_create()
{
CUTE_SYNC_ASSERT(sizeof(pthread_cond_t) <= sizeof(cute_cv_t));
cute_cv_t cv;
pthread_cond_init((pthread_cond_t*)&cv, NULL);
return cv;
}
int cute_cv_wake_all(cute_cv_t* cv)
{
pthread_cond_broadcast((pthread_cond_t*)cv);
return 1;
}
int cute_cv_wake_one(cute_cv_t* cv)
{
pthread_cond_signal((pthread_cond_t*)cv);
return 1;
}
int cute_cv_wait(cute_cv_t* cv, cute_mutex_t* mutex)
{
return !pthread_cond_wait((pthread_cond_t*)cv, (pthread_mutex_t*)mutex);
}
void cute_cv_destroy(cute_cv_t* cv)
{
pthread_cond_destroy((pthread_cond_t*)cv);
}
#if !defined(__APPLE__)
cute_semaphore_t cute_semaphore_create(int initial_count)
{
cute_semaphore_t semaphore;
semaphore.id = CUTE_SYNC_ALLOC(sizeof(sem_t), NULL);
sem_init((sem_t*)semaphore.id, 0, (unsigned)initial_count);
semaphore.count.i = initial_count;
return semaphore;
}
int cute_semaphore_post(cute_semaphore_t* semaphore)
{
return !sem_post((sem_t*)semaphore->id);
}
int cute_semaphore_try(cute_semaphore_t* semaphore)
{
return !sem_trywait((sem_t*)semaphore->id);
}
int cute_semaphore_wait(cute_semaphore_t* semaphore)
{
return !sem_wait((sem_t*)semaphore->id);
}
int cute_semaphore_value(cute_semaphore_t* semaphore)
{
int result = 0;
sem_getvalue((sem_t*)semaphore->id, &result);
return result;
}
void cute_semaphore_destroy(cute_semaphore_t* semaphore)
{
sem_destroy((sem_t*)semaphore->id);
CUTE_SYNC_FREE(semaphore->id, NULL);
}
#elif defined(__APPLE__)
// Because Apple sucks and deprecated posix semaphores we must make our own...
typedef struct cute_apple_sem_t
{
int count;
int waiting_count;
cute_mutex_t lock;
cute_cv_t cv;
} cute_apple_sem_t;
cute_semaphore_t cute_semaphore_create(int initial_count)
{
cute_apple_sem_t* apple_sem = (cute_apple_sem_t*)CUTE_SYNC_ALLOC(sizeof(cute_apple_sem_t), NULL);
apple_sem->count = initial_count;
apple_sem->waiting_count = 0;
apple_sem->lock = cute_mutex_create();
apple_sem->cv = cute_cv_create();
cute_semaphore_t semaphore;
semaphore.id = (void*)apple_sem;
semaphore.count.i = initial_count;
return semaphore;
}
int cute_semaphore_post(cute_semaphore_t* semaphore)
{
cute_apple_sem_t* apple_sem = (cute_apple_sem_t*)semaphore->id;
cute_lock(&apple_sem->lock);
if (apple_sem->waiting_count > 0) {
cute_cv_wake_one(&apple_sem->cv);
}
apple_sem->count += 1;
cute_unlock(&apple_sem->lock);
return 1;
}
int cute_semaphore_try(cute_semaphore_t* semaphore)
{
cute_apple_sem_t* apple_sem = (cute_apple_sem_t*)semaphore->id;
int result = 0;
cute_lock(&apple_sem->lock);
if (apple_sem->count > 0) {
apple_sem->count -= 1;
result = 1;
}
cute_unlock(&apple_sem->lock);
return result;
}
int cute_semaphore_wait(cute_semaphore_t* semaphore)
{
cute_apple_sem_t* apple_sem = (cute_apple_sem_t*)semaphore->id;
int result = 1;
cute_lock(&apple_sem->lock);
while (apple_sem->count == 0 && result) {
result = cute_cv_wait(&apple_sem->cv, &apple_sem->lock);
}
apple_sem->waiting_count -= 1;
if (result) {
apple_sem->count -= 1;
}
cute_unlock(&apple_sem->lock);
return result;
}
int cute_semaphore_value(cute_semaphore_t* semaphore)
{
cute_apple_sem_t* apple_sem = (cute_apple_sem_t*)semaphore->id;
int value;
cute_lock(&apple_sem->lock);
value = apple_sem->count;
cute_unlock(&apple_sem->lock);
return value;
}
void cute_semaphore_destroy(cute_semaphore_t* semaphore)
{
cute_apple_sem_t* apple_sem = (cute_apple_sem_t*)semaphore->id;
while (apple_sem->waiting_count > 0) {
cute_cv_wake_all(&apple_sem->cv);
CUTE_SYNC_YIELD();
}
cute_cv_destroy(&apple_sem->cv);