信号量是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>;

335

被折叠的 条评论
为什么被折叠?



