c++ binary_semaphore 使用详解

65 阅读1分钟

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;

// 初始计数为 0
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;
}