CX Framework
Cross-platform C utility framework
Loading...
Searching...
No Matches
sema.h
1#pragma once
2
3#include <cx/cx.h>
4#include <cx/thread/atomic.h>
5#include <cx/time/time.h>
6#include <cx/utils/macros.h>
7#include "futex.h"
8#include "aspin.h"
9
10enum SEMA_Flags {
11 SEMA_NoSpin = 0x00000001,
12};
13
14typedef struct Semaphore {
15 Futex ftx;
16 AdaptiveSpin aspin;
17} Semaphore;
18
19void _semaInit(_Out_ Semaphore *sema, int32 count, uint32 flags);
20#define semaInit(sema, count, ...) _semaInit(sema, count, opt_flags(__VA_ARGS__))
21bool semaDestroy(_Pre_valid_ _Post_invalid_ Semaphore *sema);
22bool semaTryDecTimeout(_Inout_ Semaphore *sema, int64 timeout);
23
24_meta_inline bool semaTryDec(_Inout_ Semaphore *sema)
25{
26 int32 curcount = atomicLoad(int32, &sema->ftx.val, Relaxed);
27 bool ret = (curcount > 0 && atomicCompareExchange(int32, strong, &sema->ftx.val, &curcount,
28 curcount - 1, Acquire, Relaxed));
29 if (ret)
30 aspinRecordUncontended(&sema->aspin);
31 return ret;
32}
33
34_meta_inline bool semaDec(_Inout_ Semaphore *sema)
35{
36 return semaTryDecTimeout(sema, timeForever);
37}
38
39_meta_inline bool semaInc(_Inout_ Semaphore *sema, int32 count)
40{
41 atomicFetchAdd(int32, &sema->ftx.val, count, Release);
42 futexWakeMany(&sema->ftx, count);
43 return true;
44}
#define timeForever
Maximum representable time value (approximately year 294,276 CE)
Definition time.h:13
Time manipulation and conversion functions.