sync.Once

今天阅读go部分源码的时候发现了一个包sync.Once

那么这个包来干什么的呢?通过百度和查看源码得知sync.Once可以控制函数只能被调用一次。不能多次重复调用。

    var confOnce sync.Once
    confOnce.Do(func() {
        log.Println("test")
    })
    confOnce.Do(func() {
        log.Println("test123")
    })

输出结果

2018/05/28 16:37:38 test 并不会打印test123

type Once struct {
    m    Mutex
    done uint32
}

内部有一个锁跟一个计数列。

func (o *Once) Do(f func()) {
    if atomic.LoadUint32(&o.done) == 1 { //如果o.done ==1 那么就什么也不执行
        return
    }
    // Slow-path.
    o.m.Lock() //上锁 
    defer o.m.Unlock()
    if o.done == 0 { // 不为1 则执行
        defer atomic.StoreUint32(&o.done, 1) //+1
        f() //执行函数
    }
}

具体实现用途暂时没想到不过看go源码中是用来初始化配置文件的

评论

暂无评论