2024-07-08 21:07:58 +08:00
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"sync"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// 互斥锁
|
2024-07-09 00:38:00 +08:00
|
|
|
|
// 保证同一时间只有一个goroutine进入临界区,其他的goroutine在等待锁的释放,多个goroutine等待同一个锁的时候,唤醒的策略是随机的
|
2024-07-08 21:07:58 +08:00
|
|
|
|
var x = 0
|
|
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
|
var lock sync.Mutex
|
|
|
|
|
|
|
|
|
|
func add() {
|
|
|
|
|
for i := 0; i < 5000; i++ {
|
|
|
|
|
lock.Lock()
|
|
|
|
|
x = x + 1
|
|
|
|
|
lock.Unlock()
|
|
|
|
|
}
|
|
|
|
|
wg.Done()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
wg.Add(2)
|
|
|
|
|
go add()
|
|
|
|
|
go add()
|
|
|
|
|
wg.Wait()
|
|
|
|
|
fmt.Println(x)
|
|
|
|
|
}
|