dongtan7998
2018-03-09 19:46
浏览 46
已采纳

对Go中的Locks / Mutex感到困惑

I am trying to build a map. Normally all read can be done in parallel, except when a write comes, than all reads need to be locked. I thought I understood how Mutex work in go but clearly I do not.

I first tried to use a RWMutex write lock:

type person struct {
    sync.RWMutex
    age int
}

func main() {
    a := person{age: 3}
    fmt.Println(a.age)
    go func() {
        a.Lock()
        time.Sleep(5 * time.Second)
        a.age = 4
        fmt.Println(a.age)
        a.Unlock()
    }()
    fmt.Println(a.age)
    fmt.Println("main", a.age)
    time.Sleep(20 * time.Second)
}

I somewhat expected that the wrote lock would lock the read operation a.age. Instead I got:

3
3
main 3
4

So I decided to add also a read lock:

func main() {
    a := person{age: 3}
    fmt.Println(a.age)
    go func() {
        a.Lock()
        a.RLock()
        time.Sleep(5 * time.Second)
        a.age = 4
        fmt.Println(a.age)
        a.Unlock()
        a.RUnlock()
    }()
    fmt.Println(a.age)
    fmt.Println("main", a.age)
    time.Sleep(20 * time.Second)
}

Even worse, I got:

3
3
main 3

Clearly I am not understanding how this works. Thanks for any help.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试构建地图。 通常,所有读取都可以并行完成,除非有写入请求,否则所有读取都需要锁定。 我以为我了解Mutex的工作原理,但显然我不知道。

我首先尝试使用RWMutex写锁:

  输入person struct {
 sync.RWMutex 
 age int 
} 
 
func main(){
a:= person {age:3} 
 fmt.Println(a.age)
 go func()  {
 a.Lock()
 time.Sleep(5 * time.Second)
 a.age = 4 
 fmt.Println(a.age)
 a.Unlock()
}()\  n fmt.Println(a.age)
 fmt.Println(“ main”,aage)
 time.Sleep(20 * time.Second)
} 
   
  
 

我有点希望写入的锁会锁定读取操作a.age。 相反,我得到了:

  3 
3 
main 3 
4 
   
 
 

所以我决定还添加一个 读取锁:

  func main(){
a:= person {age:3} 
 fmt.Println(a.age)
 go func(){\  n a.Lock()
 a.RLock()
 time.Sleep(5 * time.Second)
 a.age = 4 
 fmt.Println(a.age)
 a.Unlock()\  n a.RUnlock()
}()
 fmt.Println(a.age)
 fmt.Println(“ main”,a.age)
 time.Sleep(20 * time.Second)
}  
   
 
 

更糟糕的是,我得到了:

  3 
3 
main 3 
  <  / pre> 
 
 

很显然,我不了解其工作原理。 感谢您的帮助。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drmeu26880 2018-03-09 19:51
    已采纳

    Never double-lock. Your issue is that you're not wrapping the reads at the end of main in locks - if they don't try to establish a lock, there is nothing to prevent them reading while something else writes (even if the write is using a lock). The lock itself is what provides mutual exclusion (MutEx), so you only get it if you use it consistently:

    func main() {
        a := person{age: 3}
        fmt.Println(a.age)
        go func() {
            a.Lock()
            time.Sleep(5 * time.Second)
            a.age = 4
            fmt.Println(a.age)
            a.Unlock()
        }()
        a.RLock()
        fmt.Println(a.age)
        fmt.Println("main", a.age)
        a.RUnlock()
        time.Sleep(20 * time.Second)
    }
    

    There is no magic happening here; it's actually the calls to Lock and RLock that do the locking. If you don't call them, nothing prevents concurrent accesses. When you call Lock, it waits until it can get the lock all to itself, then it locks it and returns. When you call RLock, it waits until there are no write locks, then grabs a (shared) read lock. It is calling those functions which provides mutual exclusion, not any magic happening behind the scenes.

    点赞 评论
  • dou11655853 2018-03-09 20:01
    type person struct {
        sync.RWMutex
        age int
    }
    
    func main() {
        a := person{age: 3}
        fmt.Println(a.age)
        go func() {
            a.Lock()
            time.Sleep(5 * time.Second)
            a.age = 4
            fmt.Println(a.age)
            a.Unlock()
        }()
        fmt.Println(a.age)
        fmt.Println("main", a.age)
        time.Sleep(20 * time.Second)
    }
    
    
    3 <- 2nd line of `main` fmt.Println(a.age) 
    3 <- after go routine fmt.Println(a.age)
    main 3 <- fmt.Println("main", a.age)
    4 <- goroutine after sleep fmt.Println(a.age)
    

    The write lock does not lock the variable and could result in a race condition. (https://blog.golang.org/race-detector)

    Locks will only synchronize access to a.age, making write access exclusive to a single goroutine at a single time. It DOES not synchronize your go routines, which will need some sort of additional synchronization. one of the most common pattern for synchronize the two would be to use a wait group:

    https://golang.org/pkg/sync/#WaitGroup

     func main() {
            var wg sync.WaitGroup
            wg.Add(1)
            a := person{age: 3}
            fmt.Println(a.age)
            go func() {
                defer wg.Done()
                a.Lock()
                time.Sleep(5 * time.Second)
                a.age = 4
                fmt.Println(a.age)
                a.Unlock()
            }()
            wg.Wait()
            fmt.Println(a.age)
        }
    

    The wait group synchronizes the two goroutines ensuring that the last print will be 4

    点赞 评论

相关推荐 更多相似问题