ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
> ### 互斥锁 ~~~ 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) } ~~~