gpt4 book ai didi

operating-system - 如何在多核上实现锁

转载 作者:行者123 更新时间:2023-12-04 08:30:32 26 4
gpt4 key购买 nike

对于单处理器,锁定算法非常简单。

Lock(threadID) {
Disable Interrupts
If lock is already owned by same thread{
Restore Interrupts
return
}
if lock is free {
make lock busy
set current thread as the owner of the lock
}
else {
add threadID to the lock queue.
}
Restore Interrupts
return
}

但是我们如何在多处理器/多核系统中实现这段代码。如果 2 个内核/进程尝试为不同的进程提供相同的锁怎么办。

最佳答案

互斥锁一般用 atomic operations 实现在单个内存值上。例如,当 0 时,锁可以是一个空闲的单词。并锁定时 1 .为了获得锁,处理器将锁定内存总线(因此其他处理器无法读取或写入内存),读取该字的最新值,将其设置为 1如果是 0 ,并解锁内存总线。解锁的话可以设置为0 .

这是一个简单的例子,没有解决当锁被竞争时会发生什么。不同的操作系统使用不同的机制来处理。 Linux 使用一种叫做 futexes 的东西.我不确定 Windows 或 Mac 是做什么的。

尽管您发布的算法是正确的,但非内核代码无法禁用 CPU 中断,因此即使在单核上,用户空间代码也倾向于使用原子操作。

关于operating-system - 如何在多核上实现锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com