小编use*_*851的帖子

如何在多核上实现锁

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

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 个内核/进程尝试为不同的进程提供相同的锁怎么办。

operating-system mutex multicore multiprocessor locks

6
推荐指数
1
解决办法
5222
查看次数

从 golang 中的通道响应填充地图值

我正在尝试根据各种 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)

我觉得我这样做不正确。有没有更好的方法使用渠道来做到这一点?任何建议将不胜感激?

游乐场:https://play.golang.org/p/sv4Qk4hEljx

concurrency dictionary channel go

5
推荐指数
1
解决办法
2956
查看次数