1#include "semaphore.hpp"
3#include <linux/futex.h>
4#include <sys/syscall.h>
12#include "libxr_def.hpp"
13#include "monotonic_time.hpp"
20int FutexWait(std::atomic<uint32_t>* word, uint32_t expected,
21 const struct timespec* timeout)
23 return static_cast<int>(syscall(SYS_futex,
reinterpret_cast<uint32_t*
>(word),
24 FUTEX_WAIT, expected, timeout,
nullptr, 0));
27int FutexWake(std::atomic<uint32_t>* word,
int count)
29 return static_cast<int>(syscall(SYS_futex,
reinterpret_cast<uint32_t*
>(word),
30 FUTEX_WAKE, count,
nullptr,
nullptr, 0));
38 semaphore_handle_->count.store(init_count, std::memory_order_release);
45 (void)semaphore_handle_->count.fetch_add(1, std::memory_order_release);
46 (void)FutexWake(&semaphore_handle_->count, 1);
51 const uint64_t deadline_ms =
52 (timeout == UINT32_MAX) ? UINT64_MAX : (MonotonicTime::NowMilliseconds() + timeout);
56 uint32_t current = semaphore_handle_->count.load(std::memory_order_acquire);
60 if (semaphore_handle_->count.compare_exchange_weak(current, current - 1U,
61 std::memory_order_acq_rel,
62 std::memory_order_relaxed))
69 timespec* ts_ptr =
nullptr;
70 if (timeout != UINT32_MAX)
72 const uint32_t remaining_ms = MonotonicTime::RemainingMilliseconds(deadline_ms);
73 if (remaining_ms == 0)
77 ts = MonotonicTime::RelativeFromMilliseconds(remaining_ms);
81 const int ans = FutexWait(&semaphore_handle_->count, 0, ts_ptr);
82 if (ans == 0 || errno == EAGAIN || errno == EINTR)
87 if (errno == ETIMEDOUT)
104 return semaphore_handle_->count.load(std::memory_order_acquire);
void Post()
释放(增加)信号量 Releases (increments) the semaphore
void PostFromCallback(bool in_isr)
从中断回调中释放(增加)信号量 Releases (increments) the semaphore from an ISR (Interrupt Service Routine)
~Semaphore()
析构信号量对象,释放资源 Destroys the semaphore object and releases resources
Semaphore(uint32_t init_count=0)
构造一个信号量对象 Constructs a semaphore object
size_t Value()
获取当前信号量的值 Gets the current value of the semaphore
ErrorCode Wait(uint32_t timeout=UINT32_MAX)
等待(减少)信号量 Waits (decrements) the semaphore
LibXR 命名空间 / LibXR namespace.
ErrorCode
定义错误码枚举 / Defines an enumeration for error codes
@ FAILED
操作失败 / Operation failed
@ OK
操作成功 / Operation successful