互斥访问和系统调用

发布于 2024-11-29 19:33:52 字数 191 浏览 2 评论 0原文

我知道在 Linux 中,互斥体被实现为下面的 futexes,并且 futex 使用比较和交换机制。通常,为了获取锁,用户空间线程不需要进行系统调用,因为锁是在用户空间中解析的。

现在我的问题是,当存在高争用并且许多线程试图同时锁定互斥体时会发生什么。然后内核是否会发生系统调用来决定向哪个线程授予互斥锁?特别是当线程优先级不同时?我自己也这么认为。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云仙小弟 2024-12-06 19:33:52

只要不存在争用,就不会进行系统调用。如果存在争用,则会进行系统调用以将线程放入睡眠队列中,然后使用该队列在互斥体空闲时查找第一个唤醒的线程。此外,在系统调用中对 futex 的值进行了调整,以便当前拥有的线程不会通过用户态“快速路径”解锁例程(这只是将 futex 重置为零或“解锁”)值),但会进行另一个系统调用来检查睡眠队列中是否有等待线程将锁所有权传递给的线程。随着更多线程争夺锁,当然会更有可能发现争用,但同样,如果没有争用,则不会进行系统调用。

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.

蓝海似她心 2024-12-06 19:33:52

Futexes 在回退到系统调用之前仅执行少量循环,因此在锁竞争较高的情况下,线程很有可能会回退到系统调用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文