Go语言——sync.Once分析

Go语言——sync.Once分析

sync.Once表示只执行一次函数。要做到这点,就需要两点:

  1. 计数器,统计函数执行次数
  2. 线程安全,保障在多G情况下,函数仍然只执行一次,比如锁。

code

import (
   "sync/atomic"
)

// Once is an object that will perform exactly one action.
type Once struct {
   m    Mutex
   done uint32
}

Once结构体证明了之前的猜想,果然有两个变量。

// Do calls the function f if and only if Do is being called for the
// first time for this instance of Once. In other words, given
//     var once Once
// if once.Do(f) is called multiple times, only the first call will invoke f,
// even if f has a different value in each invocation. A new instance of
// Once is required for each function to execute.
//
// Do is intended for initialization that must be run exactly once. Since f
// is niladic, it may be necessary to use a function literal to capture the
// arguments to a function to be invoked by Do:
//     config.once.Do(func() { config.init(filename) })
//
// Because no call to Do returns until the one call to f returns, if f causes
// Do to be called, it will deadlock.
//
// If f panics, Do considers it to have returned; future calls of Do return
// without calling f.
//
func (o *Once) Do(f func()) {
   if atomic.LoadUint32(&o.done) == 1 {
      return
   }
   // Slow-path.
   o.m.Lock()
   defer o.m.Unlock()
   if o.done == 0 {
      defer atomic.StoreUint32(&o.done, 1)
      f()
   }
}

Do方法相当简单,但是也是有可以学习的地方。

  1. 首先原子load函数执行次数,如果已经执行过了,就return
  2. lock
  3. 执行函数
  4. 原子store函数执行次数1
  5. unlock

如果我写一般就直接先加锁,然后比较函数执行次数。而这里用原子操作可以提高性能,学习了。

一些标志位可以通过原子操作表示,避免加锁,提高性能。

    原文作者:陈先生_9e91
    原文地址: https://www.jianshu.com/p/28d19dd9bf5c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞