duan89197 2019-06-18 09:55
浏览 77

带互斥锁的竞争条件以及在何处嵌入锁,父结构或子结构?

  1. I see some people out some mutexes within a single struct. Is it necessary? Or can we simply put one single lock there? example:
type Session struct {
    // some other irrelevant code
    pingLock sync.Mutex
    // some other irrelevant code
    streamLock sync.Mutex
    // some other irrelevant code
    shutdownLock sync.Mutex
}
  1. If a struct contains another struct, and the child struct contains a map or a slice, where should I put the mutex, the parent struct or the child struct?
  2. Why is the mutex.Lock() not working in my code? Every time I run race test it shows there are races.

At first I was trying to solve the first two problems so I wrote some demo code to test it out. I tried to use the lock within the child struct ,then parent struct to lock the state, but none of them worked. The race test keeps saying there is race condition. I've tried both t.Lock() and t.data.Lock().

type Test struct {
    name string
    data Data
    sync.RWMutex //Should I put it here?
}

type Data struct {
    d map[string]int
    sync.RWMutex // Should I put it here?
}

func (t *Test) add(key string) {
    t.data.Lock()
    defer t.data.Unlock()
    t.data.d[key] += 1
}

func (t *Test) read() {
    for {
        t.data.Lock()
        _= t.data.d["test"]
        t.data.Unlock()
    }
}

func main() {

    t := &Test{}
    t.name = "oops"
    t.data = Data{}
    t.data.d = make(map[string]int)
    t.data.d["test"] = 1

    for i := 0; i <= 10; i++ {
        go func(t *Test) {
            t.add("test")
        }(t)
        go func(t *Test) {
            t.read()
        }(t)
    }
    time.Sleep(time.Second * 3)
    fmt.Printf("result is %v", t.data.d["test"])
  • 写回答

2条回答 默认 最新

  • doudao2407 2019-06-18 12:39
    关注

    The race test keeps saying there is race condition.


    The statement

    fmt.Printf("result is %v", t.data.d["test"])
    

    passes the argument

    t.data.d["test"]
    

    by value. It makes a copy by assignment, which is a read.

    You need to protect the read via the mutex.

    t.data.Lock()
    fmt.Printf("result is %v
    ", t.data.d["test"])
    t.data.Unlock()
    
    评论

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)