并发和同步

包含信号量,互斥锁等相关接口

signal.hpp

信号的值默认允许为0-31。在Linux上,由于glibc POSIX 实现中使用了某些实时信号,所以允许的值实际为0到SIGRTMAX-SIGRTMIN,在我的电脑上这个值为30。应该不会有人丧心病狂到在一个线程中使用32种信号来同步吧。

合理的使用方式是在你的模块中声明一个从0开始的枚举变量,每个枚举值对应一个信号,而且只在此模块的线程中使用。

此外,在某些系统(特别是FreeRTOS)上,相比于使用semaphore,使用signal可以在同步时节约大量的性能开销。

bool System::Signal::Wait(int sig, uint32_t timeout)

功能

等待一个信号

返回值

  • bool true:success false:timeout

参数

  • int sig 要等待的信号
  • uint32_t timeout 最大超时时间

bool System::Signal::Action(int sig, System::Thread& thread)

功能

向线程发送一个信号

返回值

  • bool true:success false:failed

参数

  • int sig 要发送的信号
  • System::Thread& thread 目标线程

semaphore.hpp

System::Semaphore(uint32_t init_value)

功能

创建一个计数信号量

参数

  • uint32_t init_value 信号量初始值

~System::Semaphore(void)

功能

销毁一个信号量

参数

  • void

void System::Semaphore::Post(void)

功能

使信号量加一

返回值

  • void

参数

  • void

bool System::Semaphore::Wait(uint32_t timeout)

功能

使信号量减一,在中断中timeout参数会被忽略

返回值

  • bool true:success false:timeout

参数

  • uint32_t timeout 最大超时时间

uint32_t System::Semaphore::Value(void)

功能

获取信号量的值

返回值

  • uint32_t 信号量的值

参数

  • void

mutex.hpp

无法在中断中使用

System::Mutex(void)

功能

创建一个互斥锁

参数

  • void

~System::Mutex(void)

功能

销毁一个互斥锁

参数

  • void

bool System::Mutex::Lock(void)

功能

互斥锁加锁

返回值

  • bool true:success false:timeout

参数

  • void

bool System::Mutex::Unlock(void)

功能

互斥锁加锁

返回值

  • bool true:success false:failed

参数

  • void