libxr  1.0
Want to be the best embedded framework
Loading...
Searching...
No Matches
semaphore.cpp
1#include "semaphore.hpp"
2
3#include <semaphore.h>
4
5#include <cstddef>
6#include <iostream>
7
8#include "libxr_def.hpp"
9
10using namespace LibXR;
11
12Semaphore::Semaphore(uint32_t init_count) : semaphore_handle_(new sem_t)
13{
14 sem_init(semaphore_handle_, 0, init_count);
15}
16
18{
19 sem_destroy(semaphore_handle_);
20 delete semaphore_handle_;
21}
22
24
25ErrorCode Semaphore::Wait(uint32_t timeout)
26{
27 struct timespec ts;
28 UNUSED(clock_gettime(CLOCK_REALTIME, &ts));
29 uint32_t secs = timeout / 1000;
30 timeout = timeout % 1000;
31
32 uint32_t add = 0;
33 int64_t raw_time = static_cast<__syscall_slong_t>(timeout * 1000U * 1000U) + ts.tv_nsec;
34 add = raw_time / (static_cast<int64_t>(1000U * 1000U * 1000U));
35 ts.tv_sec += (add + secs);
36 ts.tv_nsec = raw_time % (static_cast<int64_t>(1000U * 1000U * 1000U));
37
38 if (sem_timedwait(semaphore_handle_, &ts) == 0)
39 {
40 return ErrorCode::OK;
41 }
42 else
43 {
44 return ErrorCode::TIMEOUT;
45 }
46}
47
49{
50 UNUSED(in_isr);
51 Post();
52}
53
55{
56 int value = 0;
57 sem_getvalue(semaphore_handle_, &value);
58 return value;
59}
void Post()
释放(增加)信号量 Releases (increments) the semaphore
Definition semaphore.cpp:23
void PostFromCallback(bool in_isr)
从中断回调中释放(增加)信号量 Releases (increments) the semaphore from an ISR (Interrupt Service Routine)
Definition semaphore.cpp:48
~Semaphore()
析构信号量对象,释放资源 Destroys the semaphore object and releases resources
Definition semaphore.cpp:17
libxr_semaphore_handle semaphore_handle_
信号量句柄 Semaphore handle
Semaphore(uint32_t init_count=0)
构造一个信号量对象 Constructs a semaphore object
Definition semaphore.cpp:12
size_t Value()
获取当前信号量的值 Gets the current value of the semaphore
Definition semaphore.cpp:54
ErrorCode Wait(uint32_t timeout=UINT32_MAX)
等待(减少)信号量 Waits (decrements) the semaphore
Definition semaphore.cpp:25
LibXR 命名空间
Definition ch32_gpio.hpp:9