What does mutex and semaphore actually do?

前端 未结 6 978
逝去的感伤
逝去的感伤 2020-12-29 11:36

I want some clarification regarding mutex and semaphore.
My question is,

  1. What mutex actually do when a thread tries to enter a region locked by a mut
6条回答
  •  无人及你
    2020-12-29 12:15

    Please take a look at: https://stackoverflow.com/a/24582076/3163691

    Yes, both mutex and semaphore are synchronizing kernel objects which when a thread tries to acquire one of them, this thread is put to sleep if that object is already owned by other thread.

    As you already guessed, this sleeping is a crucial feature because it allows other threads to do more useful work than just 'looping/polling'.

    The sleeping of one of these threads ends when the thread who owns the object release it.

    [OS Scheduler doesn't give any execution slice to sleeping threads].

    Contrast it with a lock & spinlock where a thread is in a 'looping/busy-waiting' state wasting precious CPU time doing almost nothing. Therefore, spinlocks should be avoided in User code. Use a critical section, mutex or semaphore instead!.

    As you can see from the above link, both objects are different and should be used in the right context which fits best.

    Think of a mutex as a lock which allows just one thread to own it. And that it has many safe attributes (ownership, termination notification, recursion, etc.).

    And, think of a semaphore as a lock which allows just a specified number of threads to own it. However, it doesn't have the many useful attributes of a mutex.

    Hope this helps.

提交回复
热议问题