package main import ( "fmt" "sync" "sync/atomic" //原子操做,比讀寫鎖和互斥鎖都要快,原子操做在用戶態,其餘鎖在內核態 "time" ) var w sync.WaitGroup var count int32 func main() { w.Add(1) start := time.Now().UnixNano() go func() { for i := 0; i < 1000000; i++ { atomic.AddInt32(&count, 1) //原子操做 } w.Done() }() for i := 0; i < 1000000; i++ { atomic.AddInt32(&count, 1) } w.Wait() end := time.Now().UnixNano() fmt.Println((end - start) / 1000 / 1000) fmt.Println(count) }
package main import ( "fmt" "sync" "time" ) var lock sync.Mutex //互斥鎖 var w sync.WaitGroup //等待子線程退出 var count int func main() { start := time.Now().UnixNano() w.Add(1) //至關於標記起一個子線程 go func() { for i := 0; i < 1000000; i++ { lock.Lock() count++ lock.Unlock() } w.Done() //至關於標記關閉一個子線程 }() for i := 0; i < 1000000; i++ { lock.Lock() count++ lock.Unlock() } w.Wait() end := time.Now().UnixNano() fmt.Println((end - start) / 1000 / 1000) fmt.Println(count) }
package main import ( "fmt" "sync" "time" ) var rwLock sync.RWMutex //讀寫鎖,讀鎖全部線程均可以同時用(除了寫線程),可是同時寫線程不能用寫鎖。用於讀多寫少。 var lock sync.Mutex var w sync.WaitGroup var count int func main() { w.Add(1) start := time.Now().UnixNano() go func() { for i := 0; i < 1000; i++ { //rwLock.Lock() //寫鎖 lock.Lock() //互斥鎖 count++ time.Sleep(5 * time.Millisecond) lock.Unlock() //rwLock.Unlock() } w.Done() }() for i := 0; i < 16; i++ { w.Add(1) go func() { for i := 0; i < 5000; i++ { //rwLock.RLock() //讀鎖 lock.Lock() time.Sleep(1 * time.Millisecond) lock.Unlock() //rwLock.RUnlock() } w.Done() }() } w.Wait() end := time.Now().UnixNano() fmt.Println((end - start) / 1000 / 1000) //fmt.Println(count) }