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 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据