Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

operating-system - 二进制信号量和互斥量之间的区别(Difference between binary semaphore and mutex)

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

  ask by Nitin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(虽然两种类型的信号量都具有完整/空状态并使用相同的API,但它们的用法却大不相同。)

Mutual Exclusion Semaphores

(互斥信号灯)
Mutual Exclusion semaphores are used to protect shared resources (data structure, file, etc..).

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

A Mutex semaphore is "owned" by the task that takes it.

(Mutex信号量由执行该任务的任务“拥有”。)

If Task B attempts to semGive a mutex currently held by Task A, Task B's call will return an error and fail.

(如果任务B尝试给任务A当前持有的互斥锁赋值,则任务B的调用将返回错误并失败。)

Mutexes always use the following sequence:

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

- SemTake
  - Critical Section
  - SemGive

Here is a simple example:

(这是一个简单的示例:)

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:

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

  • Task B is pended waiting for something to happen (a sensor being tripped for example).

    (等待任务B等待某事发生(例如,传感器跳闸)。)

  • Sensor Trips and an Interrupt Service Routine runs.

    (传感器跳闸并运行中断服务程序。)

    It needs to notify a task of the trip.

    (它需要通知行程任务。)

  • Task B should run and take appropriate actions for the sensor trip.

    (任务B应该运行并为传感器跳闸采取适当的措施。)

    Then go back to waiting.

    (然后回到等待状态。)


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

Note that with a binary semaphore, it is OK for B to take the semaphore and A to give it.

(请注意,对于二进制信号量,B可以接收信号量,而A可以给出信号量。)
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.

(对于相同的二进制信号量来说,相同的任务通常没有什么意义。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...