📅  最后修改于: 2021-01-02 08:39:17             🧑  作者: Mango
互斥锁或互斥锁可用于同步对状态的访问,并跨许多goroutine安全地访问数据。它充当代码关键部分入口的保护,因此一次只能有一个线程进入关键部分。
我们用它在特定代码行周围设置了锁。当一个Goroutine持有锁时,所有其他Goroutine均被阻止执行受同一互斥锁保护的任何代码行,并被迫等待直到产生锁之后才能继续执行。
Go Mutex示例
package main
import (
"sync"
"time"
"math/rand"
"fmt"
)
var wait sync.WaitGroup
var count int
var mutex sync.Mutex
func increment(s string) {
for i :=0;i<10;i++ {
mutex.Lock()
x := count
x++;
time.Sleep(time.Duration(rand.Intn(10))*time.Millisecond)
count = x;
fmt.Println(s, i,"Count: ",count)
mutex.Unlock()
}
wait.Done()
}
func main(){
wait.Add(2)
go increment("foo: ")
go increment("bar: ")
wait.Wait()
fmt.Println("last count value " ,count)
}
输出:
bar: 0 Count: 1
bar: 1 Count: 2
bar: 2 Count: 3
bar: 3 Count: 4
bar: 4 Count: 5
bar: 5 Count: 6
bar: 6 Count: 7
bar: 7 Count: 8
bar: 8 Count: 9
bar: 9 Count: 10
foo: 0 Count: 11
foo: 1 Count: 12
foo: 2 Count: 13
foo: 3 Count: 14
foo: 4 Count: 15
foo: 5 Count: 16
foo: 6 Count: 17
foo: 7 Count: 18
foo: 8 Count: 19
foo: 9 Count: 20
last count value 20