问题
I know the functionality of Mutex. But now I am confused about its timing. I specially mean in the Linux kernel code.
For example, we have 3 threads (let's say they are on the same processor and are all normal tasks with the same priorities). Thread 1 ,2 and 3 try to acquire the Mutex and only Thread 1 gets it. Thread 2 and 3 are blocked and go to sleep. Then Thread 1 has done his job and unlock the Mutex.
So here is my question: At this very moment, what will happen? Will Thread 1 continue to execute because its scheduled time slice is not used up? Or will Thread 2 acquire the lock immediately and start to execute because it is the second thread who wants to acquire the lock? Or will Thread 3 acquire the lock immediately and start to execute because it is assumed to run next from the task scheduler(Let's assume this)? What will happen?
回答1:
Once Thread 1 releases the lock, what happens next is non-deterministic. Any of the scenarios you outlined above are possible.
If your application requires a very specific order among threads, then you might want to try having the threads communicate more explicitly among themselves. In C, you can do this with a pipe()
.
Generally though, the performance is best if you embrace the chaos and let the scheduler choose.
回答2:
Once Thread 1 has done his job, he gives the MUTEX back to others, and goes to sleep.
来源:https://stackoverflow.com/questions/12784182/what-is-the-mutex-acquire-and-release-order