drus39136 2017-12-16 03:48
浏览 64
已采纳

二维切片的线程安全性,其中每个线程在第一维上都有自己的索引

I am trying to ultimately end up with a 2D slice where the first dimension is equal to the number of go-routines used and the second dimension is a list of structs that each go-routine is responsible for writing to.

Type:

[][]*Node

Each go-routine will be given an index for the first dimension in the 2d slice and will only append to the list at it's index.

My first instinct was to think this was ok, but if two go-routines simultaneously need to append to their respective lists, this means I am concurrently writing to the first dimension slice.

I was thinking pointers to the second list instead of using raw lists might mitigate this concurrent write... something like:

workCollector := make([]*[]*Node, 5)
for i ; i < 5; i++ {
    go.Process(i)
}

func Process(threadNum int){
    localList := workCollector[threadNum]
    *localList = append(*localList, NewNode(UUID.()))
}

Is this enough to allow each go-routine to append to their own list or should the append happen in a mutex?

  • 写回答

1条回答 默认 最新

  • dsdsds12222 2017-12-16 05:49
    关注

    Provided that your number of goroutines is constant and each goroutine is only changing its "own" data, then your original approach is thread-safe.

    My first instinct was to think this was ok, but if two go-routines simultaneously need to append to their respective lists, this means I am concurrently writing to the first dimension slice.

    You may be concurrently writing to that slice but you're updating different indices in the backing array and provided you don't need to grow that slice, the backing array won't move.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路