package main import ( "fmt" "sync" "runtime" ) var counter int = 0 func Count(lock *sync.Mutex) { lock.Lock() counter++ fmt.Println(counter) lock.Unlock() } func main() { lock := &sync.Mutex{} for i:=0;i<10;i++ { go Count(lock) // 并发执行 } for { lock.Lock() // 锁定 c := counter lock.Unlock() // 解锁 runtime.Gosched() // 把时间片让给别人 if c >= 10 { break } } }
有疑问加站长微信联系(非本文作者)