duanlu2935 2019-05-24 21:53
浏览 22
已采纳

我应该用互斥保护结构对象吗?

I use 4 go routines to assign different member variables of a struct instance. Each member variable is only accessed by one go routine.

Do I need to add mutex when accessing the struct instance?

I am not sure if the 4 go routines access the same memory. I feel I should be cause all of them accesses the holder.

This code demonstrates what I'm doing.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    var res Response

    var mu sync.Mutex

    wg.Add(1)
    go func() {

        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.A = []string{"a"}
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.B = "b"
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.C = 100
    }()

    wg.Add(1)
    go func() {
        defer wg.Done()
        mu.Lock()
        defer mu.Unlock()
        res.D = map[string]string{
            "d": "dd",
        }
    }()

    wg.Wait()

    fmt.Println(res)

}

type Response struct {
    A []string
    B string
    C int
    D map[string]string
}
  • 写回答

1条回答 默认 最新

  • duanji1043 2019-05-26 09:32
    关注

    You do not need a mutex for this program. As far as the Go memory model is concerned, separate fields of a struct are separate variables. Since the four goroutines are accessing four separate (sub-)variables, there is no data race, even without the mutex.

    You can verify this by removing the mutex and running your program with the race detector enabled: https://golang.org/doc/articles/race_detector.html

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

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿