问题
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