进程、线程同步互斥学习 —— 信号量

本文介绍了C++中的信号量对象,作为同步和资源限制的工具。信号量能维持一个0到最大值的计数,用于控制允许访问共享资源的线程数量。文章详细讲解了创建、等待和释放信号量的过程,并通过代码示例展示了其工作原理。
摘要由CSDN通过智能技术生成

关于信号量,先看MSDN介绍:

Semaphore Objects
A semaphore object is a synchronization object that maintains a count between zero and a specified maximum value. The count is decremented each time a thread completes a wait for the semaphore object and incremented each time a thread releases the semaphore. When the count reaches zero, no more threads can successfully wait for the semaphore object state to become signaled. The state of a semaphore is set to signaled when its count is greater than zero, and nonsignaled when its count is zero.The semaphore object is useful in controlling a shared resource that can support a limited number of users. It acts as a gate that limits the number of threads sharing the resource to a specified maximum number.

 For example, an application might place a limit on the number of windows that it creates. It uses a semaphore with a maximum count equal to the window limit, decrementing the count whenever a window is created and incrementing it whenever a window is closed.

即:信号量不同于临界区,信号量可以限定一定数量线程去执行关键代码,通过P(Wait)、V(Signal)操作来实现对当前可执行关键代码线程的管理。当信号量大于0时为有信号状态,等于0为无信号状态。线程对信号量操作可以影响信号量中的计数器,通过计数器可以控制线程进入关键代码的数量。


初始化

A thread uses the CreateSemaphore

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值