WaitGroup鎖
尚硅谷Golang課

WaitGroup鎖

讀寫鎖

var x = 0
var wg sync.WaitGroup
var rwlock sync.RWMutex

func write() {
	rwlock.Lock()
	x = x + 1
	time.Sleep(time.Millisecond * 10)
	rwlock.Unlock()
	wg.Done()
}

func read() {
	// lock.Lock()
	rwlock.RLock() //鎖讀
	time.Sleep(time.Millisecond)
	rwlock.RUnlock()
	// lock.Unlock()
	wg.Done()
}

func main() {
	start := time.Now()
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go write()
	}
	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go read()
	}
	wg.Wait()
	end := time.Now()
	fmt.Println(end.Sub(start))
}

互斥鎖

var x = 0
var wg sync.WaitGroup
var lock sync.Mutex

func add() {
	for i := 0; i < 50000; i++ {
		lock.Lock()
		x = x + 1
		lock.Unlock()
	}
	wg.Done()
}

func main() {
	wg.Add(2)
	go add()
	go add()
	wg.Wait()
	fmt.Println(x)
}

上次修改於 2021-08-01

此篇文章的評論功能已經停用。