并发支持库(6)-信号量

信号量是c++提供的一种同步机制,允许一定数量的线程同时访问资源。

counting_semaphore

counting_semaphore是一个轻量级的同步原语,能控制对共享资源的访问。

template< std::ptrdiff_t LeastMaxValue>
class counting_semaphore;

和mutex同一时间只能允许一个线程访问共享资源不同,counting_semaphore允许多个线程对同一资源的并发访问,至少允许LeastMaxValue个线程同时访问。

构造counting_semaphore对象时会初始化一个内部计算器,调用acquire会让计数器减一,调用release会让计数器加一。当计数器的值为零时,调用acquire会阻塞,直到计数器增加。调用try_acquire不会阻塞,调用try_acquire_for和try_acquire_until会阻塞至计数器增加或者达到时间限制。

代码示例:

std::counting_semaphore<5> semaphore{0};
std::jthread t = std::jthread(
    [&]()
    {
        semaphore.acquire();
        std::cout << "subthread" << std::endl;
        semaphore.release();
    });

std::cout << "main thread" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
semaphore.release();

输出结果:

main thread
subthread

binary_semaphore

binary_semaphore是counting_semaphore特化的别名:

using binary_semaphore = counting_semaphore<1>;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lucy_stone

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值