go-互斥锁及原子函数

时间:2022-10-29 10:48:28

用于解决并发函数的竞争状态问题。。。

package main

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

var (
	counter int64
	wg      sync.WaitGroup
	mutex   sync.Mutex
)

func main() {

	wg.Add(2)

	fmt.Println("Create Goroutines")
	go incCount(1)
	go incCount(2)

	fmt.Println("Waiting To Finish")
	wg.Wait()

	fmt.Println("Final Counter: ", counter)

}

func incCount(id int) {
	defer wg.Done()
	for count := 0; count < 2; count++ {
		atomic.AddInt64(&counter, 1)
		//value := counter
		runtime.Gosched()
		//value++
		//counter = value
	}

	mutex.Lock()
	{
		value := counter
		runtime.Gosched()
		value++
		counter = value
	}
	mutex.Unlock()
}