How is a thread waiting for mutex put back to running?

我们两清 提交于 2021-02-08 10:28:59

问题


The context is like this:

  • a thread tries to lock a already locked mutex
  • the thread is put to sleep/blocking
  • after some while, the mutex is unlocked

Q1) What will happen then ?

will the thread be immediately put back to running? Or kernel will still wait the running thread consume its time slice and schedule the waiting thread normally?

Q2) What if the mutex is not unlocked forever? How does the kernel determine to keep the thread waiting?


回答1:


Will the thread be immediately put back to running? Or kernel will still wait the running thread consume its time slice and schedule the waiting thread normally?

Typically the thread is now ready-to-run. On most systems, if there's an available core, it will begin running immediately. If not, then it will be considered the next time the scheduler is invoked on any core.

What if the mutex is not unlocked forever? How does the kernel determine to keep the thread waiting?

Typically, the first thing the thread does when it wakes up is try to lock the mutex. If it fails, it blocks again. Some implementations assign the mutex to a particular thread before they make it ready-to-run, in which case the thread wakes up with the mutex.

Implementations vary and may do anything that conforms to the requirements.



来源:https://stackoverflow.com/questions/42365744/how-is-a-thread-waiting-for-mutex-put-back-to-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!