Go语言中解决多协程对共享资源进行竞争的方式

lock用来解决多协程对共享资源进行竞争

优点:比较灵活,可以针对代码段加锁

package main

import (
	"fmt"
	"sync"
)

// lock用来解决多协程对共享资源进行竞争

var total int32
var wg sync.WaitGroup
var lock sync.Mutex

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

func dec() {
	defer wg.Done()
	for i := 0; i < 10000; i++ {
		lock.Lock()
		total -= 1
		lock.Unlock()
	}
}

func main() {
	wg.Add(2)
	go add()
	go dec()
	wg.Wait()
	fmt.Printf("done all total %d\n", total)

}

//--- done all total 0

用go内置的原子操作函数来实现

package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

// lock用来解决多协程对共享资源进行竞争

var total int32
var wg sync.WaitGroup

// var lock sync.Mutex

func add() {
	defer wg.Done()
	for i := 0; i < 10000; i++ {
		//lock.Lock()
		//total += 1
		//lock.Unlock()
		// 直接使用原子操作
		atomic.AddInt32(&total, 1)
	}
}

func dec() {
	defer wg.Done()
	for i := 0; i < 10000; i++ {
		//lock.Lock()
		//total -= 1
		//lock.Unlock()
		atomic.AddInt32(&total, -1)
	}
}

func main() {
	wg.Add(2)
	go add()
	go dec()
	wg.Wait()
	fmt.Printf("done all total %d\n", total)

}

//--- done all total 0