对于单处理器,锁定算法非常简单。
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
}
Run Code Online (Sandbox Code Playgroud)
但是我们如何在多处理器/多核系统中实现这段代码。如果 2 个内核/进程尝试为不同的进程提供相同的锁怎么办。
我正在尝试根据各种 goroutine 的输出来填充地图。为此,我创建了一个类型为 (map[key][]int) 的通道
done := make(chan map[int][]int)
Run Code Online (Sandbox Code Playgroud)
并将其与键值一起传递给工人 goroutine,在示例中键值是 int。对于我:= 0;我<10;i++ { goworker(i,done) } 我想在从键读取时填充我的地图。目前我正在做如下
for i := 0; i < 10; i++ {
m := <-done
fmt.Println(m)
for k,v := range m {
retmap[k] = v
}
}
fmt.Println(retmap)
Run Code Online (Sandbox Code Playgroud)
我觉得我这样做不正确。有没有更好的方法使用渠道来做到这一点?任何建议将不胜感激?