二进制信号量和互斥量之间的区别 [英] Difference between binary semaphore and mutex

查看:293
本文介绍了二进制信号量和互斥量之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

二进制信号量和互斥量之间是否有区别,或者它们本质上是相同的?

Is there any difference between a binary semaphore and mutex or are they essentially the same?

推荐答案

它们是同一件事.它们用于不同的目的!
虽然两种类型的信号量都具有完整/空状态并使用相同的API,但它们的用法却大不相同.

They are NOT the same thing. They are used for different purposes!
While both types of semaphores have a full/empty state and use the same API, their usage is very different.

互斥信号量
互斥信号量用于保护共享资源(数据结构,文件等).

Mutual Exclusion Semaphores
Mutual Exclusion semaphores are used to protect shared resources (data structure, file, etc..).

互斥量信号量由接收它的任务拥有".如果任务B尝试给任务A当前持有的互斥锁赋值,则任务B的调用将返回错误并失败.

A Mutex semaphore is "owned" by the task that takes it. If Task B attempts to semGive a mutex currently held by Task A, Task B's call will return an error and fail.

互斥对象始终使用以下顺序:

Mutexes always use the following sequence:


  - SemTake
  - Critical Section
  - SemGive

这是一个简单的例子:


  Thread A                     Thread B
   Take Mutex
     access data
     ...                        Take Mutex  <== Will block
     ...
   Give Mutex                     access data  <== Unblocks
                                  ...
                                Give Mutex

二进制信号量
二进制信号量解决了一个完全不同的问题:

Binary Semaphore
Binary Semaphore address a totally different question:

  • 等待任务B挂起,等待某事发生(例如,传感器跳闸).
  • 传感器跳闸并运行中断服务程序.它需要通知任务的行程.
  • 任务B应该运行并为传感器跳闸采取适当的措施.然后回到等待状态.

   Task A                      Task B
   ...                         Take BinSemaphore   <== wait for something
   Do Something Noteworthy
   Give BinSemaphore           do something    <== unblocks

请注意,对于二进制信号量,B可以接受信号量,而A可以提供信号量.
同样,二进制信号量不能保护资源免于访问.发出信号量和接收信号量的行为从根本上是分离的.
通常,对同一任务执行相同的二进制信号量的取舍没有多大意义.

Note that with a binary semaphore, it is OK for B to take the semaphore and A to give it.
Again, a binary semaphore is NOT protecting a resource from access. The act of Giving and Taking a semaphore are fundamentally decoupled.
It typically makes little sense for the same task to so a give and a take on the same binary semaphore.

这篇关于二进制信号量和互斥量之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆