dongpo1203 2016-10-27 21:38
浏览 42
已采纳

将append()附加到另一个线程正在读取的切片上是否安全?

Let's say I have many goroutines doing something like this:

func (o *Obj) Reader() {
  data := o.data;
  for i, value := range data {
    log.Printf("got data[%v] = %v", i, value)
  }
}

And one doing this:

func (o *Obj) Writer() {
    o.data = append(o.data, 1234)
}

If data := o.data means the internal structure of the slice is copied, this looks like it could be safe, because I'm never modifying anything in the accessible range of the copy. I'm either setting one element outside of the range and increasing the length, or allocating a completely new pointer, but the reader would be operating on the original one.

Are my assumptions correct and this is safe to do?

I'm aware that slices are not meant to be "thread-safe" in general, the question is more about how much does slice1 := slice2 actually copy.

  • 写回答

2条回答 默认 最新

  • doushi6947 2016-10-27 22:20
    关注

    The code in the question is unsafe because it reads a variable in one goroutine and modifies the variable in another goroutine without synchronization.

    Here's one way to make the code safe:

    type Obj struct {
       mu sync.Mutex // add mutex
       ... // other fields as before
    }
    
    func (o *Obj) Reader() {
        o.mu.Lock()
        data := o.data
        o.mu.Unlock()
        for i, value := range data {
          log.Printf("got data[%v] = %v", i, value)
        }
    }
    
    func (o *Obj) Writer() {
         o.mu.Lock()
         o.data = append(o.data, 1234)
         o.mu.Unlock()
    }
    

    It's safe for Reader to range over the local slice variable data because the Writer does not modify the local variable data or the backing array visible through the local variable data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大