Go の 竞争状态



如果多个 goroutine 同时读写某个资源,那么他们就处于相互竞争的状态,这种情况被称为竞争状态

1.原子函数

package main

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

var (
	wg       sync.WaitGroup
	shutdown int64
)

func f1(name string) {
	defer wg.Done()
	for {
		fmt.Println(name)
		if atomic.LoadInt64(&shutdown) == 1 {
			fmt.Println("等于1了,不用打印了")
			break
		}
	}
}

func main() {
	wg.Add(2)
	go f1("A")
	go f1("B")
	fmt.Println("该停止工作了")
	atomic.StoreInt64(&shutdown, 1)
	wg.Wait()

}



2.互斥锁

package main

import (
	"fmt"
	"runtime"
	"sync"
)

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

func f1() {
	defer wg.Done()
	for i := 0; i < 5; i++ {
		mutex.Lock()
		{
			value := counter
			runtime.Gosched()
			value++
			counter = value
		}
		mutex.Unlock()
	}
}

func main() {
	wg.Add(2)
	go f1()
	fmt.Println(counter)
	go f1()
	wg.Wait()
	fmt.Println(counter)
}

posted @ 2021-04-16 15:08  沧海一声笑rush  阅读(35)  评论(0编辑  收藏  举报