c++ binary_semaphore 使用详解
std::binary_semaphore c++20
- 头文件
#include <semaphore>
。
- 作用:二进制信号量,轻量同步元件,能控制对共享资源的互斥访问。
std::binary_semaphore 成员函数
release
:增加内部计数器并解除阻塞者。
acquire
:阻塞直到能减少内部计数器为止。
try_acquire
:尝试减少内部计数器。
try_acquire_for
:尝试减少内部计数器,失败则阻塞一段时长(可通过 release 解除阻塞)。
try_acquire_until
:尝试减少内部计数器,失败则阻塞至一个时间点(可通过 release 解除阻塞)。
示例代码
#include <cstdio>
#include <thread>
#include <chrono>
#include <semaphore>
using namespace std::literals;
std::binary_semaphore sem(0);
void ThreadProc()
{
sem.acquire();
printf("thread get sem\n");
std::this_thread::sleep_for(1s);
printf("thread send sem\n");
sem.release();
}
int main()
{
std::jthread thrWorker(ThreadProc);
printf("main send sem\n");
sem.release();
std::this_thread::sleep_for(1ms);
sem.acquire();
printf("main get sem\n");
return 0;
}