//读写互斥锁 package main import ( "fmt" "sync" "time" ) var ( x = 0 wg sync.WaitGroup lock sync.Mutex rwLock sync.RWMutex ) //读操作加读锁 func read() { defer wg.Done() rwLock.RLock() fmt.Println(x) time.Sleep(time.Millisecond) rwLock.RUnlock() } func write() { defer wg.Done() rwLock.Lock() fmt.Println(x) x = x + 1 time.Sleep(time.Millisecond) rwLock.Unlock() } func main() { start := time.Now() for i := 0; i < 100; i++ { go write() wg.Add(1) } for i := 0; i < 1000; i++ { go read() wg.Add(1) } wg.Wait() fmt.Println(time.Now().Sub(start)) }