What does mutex and semaphore actually do?

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

    It depends on the type of mutex (its backing implementation), some have busy spinning with back-off, others will just sleep the kernel thread object which will then later be woken when the mutex is updated and some are a hybrid of the two (Valve's Source engine uses the hybrid ones). Its characteristics also depend on when and how often it needs to cross kernel/userspace barriers, as sometimes this can be more costly than just spinning a little longer (see this if you want to get more into the spinning vs sleeping side of things).

    Mutexes are generally for single thread entry at a time (though they may support recursive entry by the same thread). Semaphores on the other hand allow only n threads at a time to try acquire it (see this MSDN writeup, or this comparative Intel writeup).

    Sleeping a thread generally means it gives up its allocation computation timeslice till its ready to be woken and the OS scheduler gives it another time slice. the best examples you are likely to find would actually be in the linux kernel source (or any other open source OS for that matter).

提交回复
热议问题