首页 > 代码库 > Go语言,用原子函数atomic避免资源竞争

Go语言,用原子函数atomic避免资源竞争

下一步应该是互斥锁了。

package mainimport (	"fmt"	"runtime"	"sync"	"sync/atomic")var (	counter int64	wg sync.WaitGroup)func main() {	wg.Add(2)		fmt.Println("Create Goroutines")	go incCounter(1)	go incCounter(2)		fmt.Println("Waiting To Finish")	wg.Wait()		fmt.Println("Final Counter:", counter)}func incCounter(id int) {	defer wg.Done()	for count := 0; count < 2; count++ {		atomic.AddInt64(&counter, 1)		runtime.Gosched()	}}

  技术分享

Go语言,用原子函数atomic避免资源竞争