ITPub博客

首页 > 应用开发 > > Differen cebetween Mutex

Differen cebetween Mutex

作者:helei1000 时间:2019-09-09 16:36:31 0 删除 编辑

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..).

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

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).

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. 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.

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.

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2613/viewspace-3138326/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    94
  • 访问量
    678