何时使用互斥锁

时间:2019-03-16 12:13:27

标签: go mutex

Go中确实需要它们吗?我已阅读https://gobyexample.com/mutexes并多次运行示例代码,当我删除mutex.Lock()mutex.Unlock()时,它们的工作原理完全相同。

3 个答案:

答案 0 :(得分:3)

  

我已阅读https://gobyexample.com/mutexes并运行示例代码   多次,当我删除mutex.Lock()和mutex.Unlock()时,它可以工作   完全一样。


正如预期的那样,当我删除互斥锁时,会出现数据争夺和恐慌。


输出:

$ go run -race racer.go

fatal error: concurrent map read and map write

==================
WARNING: DATA RACE
Write at 0x00c00009a690 by goroutine 113:
  runtime.mapassign_fast64()
      /home/peter/go/src/runtime/map_fast64.go:92 +0x0
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xba

Previous read at 0x00c00009a690 by goroutine 64:
  runtime.mapaccess1_fast64()
      /home/peter/go/src/runtime/map_fast64.go:12 +0x0
  main.main.func1()
      /home/peter/gopath/src/so/racer.go:37 +0x72

Goroutine 113 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124

Goroutine 64 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:29 +0xe0
==================
==================
WARNING: DATA RACE
Write at 0x00c00009a690 by goroutine 115:
  runtime.mapassign_fast64()
      /home/peter/go/src/runtime/map_fast64.go:92 +0x0
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xba

Previous read at 0x00c00009a690 by goroutine 39:
  runtime.mapaccess1_fast64()
      /home/peter/go/src/runtime/map_fast64.go:12 +0x0
  main.main.func1()
      /home/peter/gopath/src/so/racer.go:37 +0x72

Goroutine 115 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124

Goroutine 39 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:29 +0xe0
==================
==================
WARNING: DATA RACE
Read at 0x00c0001f0048 by goroutine 79:
  main.main.func1()
      /home/peter/gopath/src/so/racer.go:37 +0x80

Previous write at 0x00c0001f0048 by goroutine 113:
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xcf

Goroutine 79 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:29 +0xe0

Goroutine 113 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124
==================
==================
WARNING: DATA RACE
Read at 0x00c0001f0050 by goroutine 81:
  main.main.func1()
      /home/peter/gopath/src/so/racer.go:37 +0x80

Previous write at 0x00c0001f0050 by goroutine 115:
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xcf

Goroutine 81 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:29 +0xe0

Goroutine 115 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124
==================
==================
WARNING: DATA RACE
Read at 0x00c0001f0050 by goroutine 106:
  main.main.func1()
      /home/peter/gopath/src/so/racer.go:37 +0x80

Previous write at 0x00c0001f0050 by goroutine 115:
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xcf

Goroutine 106 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:29 +0xe0

Goroutine 115 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124
==================
==================
WARNING: DATA RACE
Read at 0x00c0001f0050 by goroutine 94:
  main.main.func1()
      /home/peter/gopath/src/so/racer.go:37 +0x80

Previous write at 0x00c0001f0050 by goroutine 115:
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xcf

Goroutine 94 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:29 +0xe0

Goroutine 115 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124
==================
==================
WARNING: DATA RACE
Write at 0x00c0001f0050 by goroutine 114:
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xcf

Previous write at 0x00c0001f0050 by goroutine 115:
  main.main.func2()
      /home/peter/gopath/src/so/racer.go:56 +0xcf

Goroutine 114 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124

Goroutine 115 (running) created at:
  main.main()
      /home/peter/gopath/src/so/racer.go:51 +0x124
==================
exit status 2
$ 

racer.go

package main

import (
    "fmt"
    "math/rand"

    //*"sync"
    "sync/atomic"
    "time"
)

func main() {

    // For our example the state will be a map.

    var state = make(map[int]int)

    // This mutex will synchronize access to state.

    //*var mutex = &sync.Mutex{}

    // We’ll keep track of how many read and write operations we do.

    var readOps uint64
    var writeOps uint64

    // Here we start 100 goroutines to execute repeated reads against the state, once per millisecond in each goroutine.

    for r := 0; r < 100; r++ {
        go func() {
            total := 0
            for {

                // For each read we pick a key to access, Lock() the mutex to ensure exclusive access to the state, read the value at the chosen key, Unlock() the mutex, and increment the readOps count.

                key := rand.Intn(5)
                //*mutex.Lock()
                total += state[key]
                //*mutex.Unlock()
                atomic.AddUint64(&readOps, 1)

                // Wait a bit between reads.

                time.Sleep(time.Millisecond)
            }
        }()
    }

    // We’ll also start 10 goroutines to simulate writes, using the same pattern we did for reads.

    for w := 0; w < 10; w++ {
        go func() {
            for {
                key := rand.Intn(5)
                val := rand.Intn(100)
                //*mutex.Lock()
                state[key] = val
                //*mutex.Unlock()
                atomic.AddUint64(&writeOps, 1)
                time.Sleep(time.Millisecond)
            }
        }()
    }

    // Let the 10 goroutines work on the state and mutex for a second.

    time.Sleep(time.Second)

    // Take and report final operation counts.

    readOpsFinal := atomic.LoadUint64(&readOps)
    fmt.Println("readOps:", readOpsFinal)
    writeOpsFinal := atomic.LoadUint64(&writeOps)
    fmt.Println("writeOps:", writeOpsFinal)

    // With a final lock of state, show how it ended up.

    //*mutex.Lock()
    fmt.Println("state:", state)
    //*mutex.Unlock()
}

答案 1 :(得分:0)

是的,go中的映射不是线程安全的。在此示例中,映射访问可能来自多个线程。从多个线程写入映射或从多个线程写入和读取映射时,将发生未定义的行为。但是,何时以及是否发生取决于时间。因此,删除互斥锁可能会在将来的某个时候导致数据损坏或崩溃。

答案 2 :(得分:0)

您无法一次通过多个go例程访问map
它可能会工作一段时间,但注定会失败或导致意外结果。

Mutex保证,只有一个go例程才能同时对LockUnlock之间的一段代码进行操作。

或者,您可以使用sync.Map,该线程对于读取和写入是线程安全的。

m := new(sync.Map)

go func() {
    for r := 0; true; r++ {
        m.Store(r, r)
        time.Sleep(time.Millisecond)
    }
}()

go func() {
    for r := 0; true; r++ {
        res, ok := m.Load(r)
        if ok {
            fmt.Println(res)
        }
        time.Sleep(10 * time.Millisecond)
    }
}()

同步。地图并不总是意味着线程安全

sync.Map的读取(Load)和写入(Store)是原子的,即立即从不同的go例程调用它们将按预期方式工作/不会破坏数据或引发错误。

但是,组成不同的sync.Map可能不是原子的,因此也不是线程安全的。

例如,

val, ok := m.Load("someKey")
if !ok {
    m.Store("someKey", LoadData())
}

如果此代码一次从不同的go例程运行,那么即使没有预期,这两个go例程也有可能进入if语句并加载数据。
因此,有时您可能最终需要使用互斥锁而不是sync.Map

val, ok := m.Load("someKey")
if !ok {
    mutex.Lock()
    defer mutex.Unlock()
    val, ok = m.Load("someKey")
    if !ok {
        m.Store("someKey", LoadData())
    }
}