Mutex access and system call

…衆ロ難τιáo~ 提交于 2019-12-20 20:19:09

问题


I know that in Linux mutexes are implemented as futexes down below and futex uses compare-and-swap mechanism. And usually for acquiring locks, a user-space thread does not need to make a system call as the lock is resolved in user-space.

Now my question is what happens when there is high contention and many threads are trying to lock a mutex at the same time. Does a system call occurs then for the kernel to decide which thread to grant the mutex? Especially when thread priorities are different? I myself think so.


回答1:


As long as there is no contention, there are no system calls made. If there is contention, then a system call is made to place the thread in a sleep queue that will then be used to find the first thread to wake up when the mutex becomes free. Additionally, an adjustment is made in the syscall to the value of the futex so that the currently owning thread will not go through the user-land "fast-path" unlock routine (which simply resets the futex back to a zero or "unlocked" value), but will instead make another system call to check the sleep queue for waiting threads to pass the lock ownership to. With more threads contending for a lock, there is of course going to be a higher chance of a contention being found, but again, if there is no contention, then there is no sys-call made.




回答2:


Futexes only do a small number of loops before falling back to a syscall, so in case of high lock contension there is a high chance that threads will fallback to a syscall.



来源:https://stackoverflow.com/questions/7067982/mutex-access-and-system-call

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