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

时间:2021-07-24 10:47:52

下一步应该是互斥锁了。

package main

import (
	"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避免资源竞争