Operating system 如何在多核上实现锁

Operating system 如何在多核上实现锁,operating-system,mutex,multicore,locks,multiprocessor,Operating System,Mutex,Multicore,Locks,Multiprocessor,对于单处理器,锁定算法非常简单 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 thread

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

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
}

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

互斥锁通常在单个内存值上实现。例如,锁可以是单个单词,当
0
时是自由的,当
1
时是锁定的。要获得锁,处理器将锁定内存总线(因此其他处理器无法读取或写入内存),读取单词的最新值,如果是
0
,则将其设置为
1
,然后解锁内存总线。要解锁,可将单词设置为
0

这是一个简单的例子,没有说明当锁被争用时会发生什么。不同的OSs使用不同的机制处理这些问题。Linux使用了一种叫做。我不确定Windows或Mac是做什么的


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

我说考虑锁的最简单方法是原子交换指令。以下命令获取锁X

LOCK: set RegisterA = 1 Atomic_Exchange(X, RegisterA) //runs such that no other thread can work with X if RegisterA == 1: Means X was 1 when I esecuted the exchange thus someone else has the lock Since I do not have the lock, goto LOCK else: If A is zero, it means I was the first one to set X to 1, which means I own the lock UNLOCK: X = 0 锁定: 设置RegisterA=1 原子交换(X,RegisterA)//运行时没有其他线程可以使用X 如果RegisterA==1: 意味着当我切断交换时X是1,因此其他人拥有锁 既然我没有锁,就去锁吧 其他: 如果A为零,这意味着我是第一个将X设置为1的人,这意味着我拥有锁 解锁: X=0
原子交换存在于大多数计算机中。英特尔x86有一条EXCHG指令用于此。仅供参考,Intel的x86还有一个比较和交换指令,可以为您处理获取和比较。基本上,它不是先进行交换,然后在软件中进行测试,而是使用硬件,仅当X==0时才进行交换。这将节省对变量X的额外写入,从而减少X的缓存未命中,从而提高性能

它只能通过原子操作完成,还是还需要系统调用(禁用中断)?