CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
sema.h
Go to the documentation of this file.
1
28
29#pragma once
30
31#include <cx/cx.h>
32#include <cx/thread/atomic.h>
33#include <cx/time/time.h>
34#include <cx/utils/macros.h>
35#include "aspin.h"
36#include "futex.h"
37
38CX_C_BEGIN
39
42 SEMA_NoSpin = 0x00000001,
43};
44
46typedef struct Semaphore {
47 Futex ftx;
48 AdaptiveSpin aspin;
50
51void _semaInit(_Out_ Semaphore* sema, int32 count, uint32 flags);
52
61#define semaInit(sema, count, ...) _semaInit(sema, count, opt_flags(__VA_ARGS__))
62
69bool semaDestroy(_Pre_valid_ _Post_invalid_ Semaphore* sema);
70
79bool semaTryDecTimeout(_Inout_ Semaphore* sema, int64 timeout);
80
87_meta_inline bool semaTryDec(_Inout_ Semaphore* sema)
88{
89 int32 curcount = atomicLoad(int32, &sema->ftx.val, Relaxed);
90 bool ret = (curcount > 0 &&
91 atomicCompareExchange(int32,
92 strong,
93 &sema->ftx.val,
94 &curcount,
95 curcount - 1,
96 Acquire,
97 Relaxed));
98 if (ret)
99 aspinRecordUncontended(&sema->aspin);
100 return ret;
101}
102
109_meta_inline bool semaDec(_Inout_ Semaphore* sema)
110{
111 return semaTryDecTimeout(sema, timeForever);
112}
113
120_meta_inline bool semaInc(_Inout_ Semaphore* sema, int32 count)
121{
122 atomicFetchAdd(int32, &sema->ftx.val, count, Release);
123 futexWakeMany(&sema->ftx, count);
124 return true;
125}
126
127CX_C_END
128
130// end of thread_sema group
Atomic operations.
bool semaTryDec(Semaphore *sema)
Definition sema.h:87
bool semaInc(Semaphore *sema, int32 count)
Definition sema.h:120
bool semaDec(Semaphore *sema)
Definition sema.h:109
bool semaTryDecTimeout(Semaphore *sema, int64 timeout)
bool semaDestroy(Semaphore *sema)
SEMA_Flags
Semaphore initialization flags.
Definition sema.h:41
@ SEMA_NoSpin
Disable adaptive spinning, use kernel futex immediately.
Definition sema.h:42
#define timeForever
Maximum representable time value (approximately year 294,276 CE)
Definition time.h:15
Counting semaphore synchronization primitive.
Definition sema.h:46
AdaptiveSpin aspin
Adaptive spin state.
Definition sema.h:48
Futex ftx
Futex holding the current count.
Definition sema.h:47
Time manipulation and conversion functions.