What is the Mutex acquire and release order?

一曲冷凌霜 提交于 2019-12-24 04:16:12

问题


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

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