Skip to content

Latest commit

 

History

History
39 lines (32 loc) · 582 Bytes

go的sync包使用.md

File metadata and controls

39 lines (32 loc) · 582 Bytes

sync.Once

sync.Once控制函数只能被调用一次,不能重复调用,底层原理是利用原子计数记录func是否被执行atomic.StoreUint32(&o.done, 1),已执行sync.Once.done会设置为1

package main

import (
	"fmt"
	"sync"
)

func main() {
	o := &sync.Once{}
	Do(o)
	Do(o)
}

func Do(o *sync.Once) {
	fmt.Println("start")
	o.Do(func() {
		fmt.Println("run....") // 只能调用一次
	})
	o.Do(func() {
        fmt.Println("re run") // 即时重置函数也不会调用
	})
	fmt.Println("end")
}

输出:

start
run....
end
start
end