What does mutex and semaphore actually do?

前端 未结 6 940
逝去的感伤
逝去的感伤 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 11:55

    Waiting, sleeping, blocking, all mean the same thing:

    1. The thread makes a system call (get a mutex or semaphore, wait for some time, whatever)

    2. The OS takes control, run the scheduler, marks the thread as waiting for a resource, updates status of other threads as well, then gives control to a thread that is ready to run. If more than one thread is ready to run, one is selected according to scheduling policy.

    3. As soon as the resource is made available (through another system call made by another thread), the scheduler updates the status of the former thread from waiting for a resource to ready to run and the thread is given control as soon as the scheduler policy decides so.

    As long as the thread is waiting for a resource, it doesn't consume CPU. There is no polling from its part.

提交回复
热议问题