golang协程并发同步-互斥锁

func main() {
	num := 0
	lock := sync.Mutex{}
	wg :=sync.WaitGroup{}
	wg.Add(2)
	go add(&num,&lock,&wg)//需要传入同一个锁
	go reduce(&num,&lock,&wg)
	wg.Wait()//等待协程完成
	fmt.Println(num)
}

func add(num *int,lock *sync.Mutex,wg *sync.WaitGroup){
	for i:=0;i<10000;i++{
		lock.Lock()
		*num += 1
		lock.Unlock()
	}
	wg.Done()
}

func reduce(num *int,lock *sync.Mutex,wg *sync.WaitGroup){
	for i:=0;i<10000;i++{
		lock.Lock()
		*num -=1
		lock.Unlock()
	}
	wg.Done()
}

你可能感兴趣的:(golang协程并发同步)