💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
> ### 互斥锁 ```go package main import ( "time" "fmt" "sync" ) var number int var mu sync.Mutex func main() { go func() { for i := 0; i < 10000; i++ { mu.Lock() number++ mu.Unlock() } }() go func() { for i := 0; i < 10000; i++ { mu.Lock() number++ mu.Unlock() } }() go func() { for i := 0; i < 10000; i++ { mu.Lock() number++ mu.Unlock() } }() time.Sleep(time.Second * 3) fmt.Println(number) } ``` > ### 可以理解为信号量,只有一个信号量, 锁代码块 ``` package main import ( "time" "fmt" "sync" ) var number1 int var number2 int var mu sync.Mutex func main() { go func() { for i := 0; i < 3; i++ { mu.Lock() number1++ fmt.Println("G1", 1) time.Sleep(time.Second) fmt.Println("G1", 2) number2++ mu.Unlock() } }() go func() { for i := 0; i < 3; i++ { mu.Lock() number2++ fmt.Println("G2", 3) time.Sleep(time.Second) fmt.Println("G2", 4) number1++ mu.Unlock() } }() time.Sleep(time.Second) go func() { for i := 0; i < 3; i++ { number2++ fmt.Println("G3", number2) } }() time.Sleep(time.Second * 10) fmt.Println(number1) fmt.Println(number2) } ```