What does mutex and semaphore actually do?

前端 未结 6 942
逝去的感伤
逝去的感伤 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:02

    1. What mutex actually do when a thread tries to enter a region locked by a mutex, a. it waits for the lock to be released? or b. it goes to sleep until the lock is released. In that case how it is wake up again when the lock is released?

    When a thread attempts to acquire a mutex lock, it is stuck and returns only if the lock is granted to that thread. The lock is recognised by OS, so OS knows that till such a lock is available to give thread - it has nothing else to do. The thread is parked inside OS. It is only the OS who knows that now the thread has ownership it goes back to sleep. In a single CPU system, at that very instance if some other process is on, the mutex lock will return only when thread has both - CPU available as well lock granted!

    Note: when you do fwrite or select same thing happens. Since OS knows that respective IO will take time, the thread becomes idle. When data arrives, the thread becomes runnable.

    1. Same question as 1, but in this case it is semaphore. Can you give me some code regarding busy waiting in pthread in C, and also a case where thread goes to sleep instead of waiting? does sleep mean it is blocked or sleeping is another kind of busy waiting?

    In both cases, there are NO busy wait. If any one would busy wait to kill time till you get lock - you have actually failed the purpose of lock! Consider this, let say we have strictly single CPU case (and a stupid OS). So what happens is, thread 1 attempts to acquire lock, since lock lies with thread B so thread A begins to do busy wait. Hence, CPU is never released from thread A and thread B never gets chance to execute on CPU - in the end both threads are in useless situation. Locks doesn't do anything on thread object. But locking process invariably park the threads

提交回复
热议问题