31 lines
458 B
Go
31 lines
458 B
Go
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"sync"
|
||
)
|
||
|
||
// 互斥锁
|
||
// 保证同一时间只有一个goroutine进入临界区,其他的goroutine在等待锁的释放,多个goroutine等待同一个锁的时候,唤醒的策略是随机的
|
||
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)
|
||
}
|