前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言——sync.Once分析

Go语言——sync.Once分析

作者头像
恋喵大鲤鱼
发布2019-03-06 11:30:55
6440
发布2019-03-06 11:30:55
举报
文章被收录于专栏:C/C++基础C/C++基础

1.简介

sync.Once表示只执行一次函数。要做到这点,就需要两点: (1)计数器,统计函数执行次数; (2)线程安全,保障在多G情况下,函数仍然只执行一次,比如锁。

代码语言:javascript
复制
import (
   "sync/atomic"
)

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

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

代码语言:javascript
复制
// 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方法相当简单,但是也是有可以学习的地方。比如一些标志位可以通过原子操作表示,避免加锁,提高性能。Do方法实现过程如下: (1)首先原子load函数执行次数,如果已经执行过了,就return; (2)lock; (3)执行函数; (4)原子store函数执行次数1; (5)unlock。

2.示例

代码语言:javascript
复制
package main

import (
        "fmt"
        "sync"
        "time"
)

var once sync.Once
var onceBody = func() {
    fmt.Println("Only once")
}

func main() {
        for i := 0; i < 10; i++ {
                go func(i int) {
                        once.Do(onceBody)
                        fmt.Println("i=",i)
                }()
        }
        time.Sleep(time.Second) //睡眠1s用于执行go程,注意睡眠时间不能太短
}

程序运行输出:

代码语言:javascript
复制
Only once
i= 3
i= 6
i= 4
i= 5
i= 7
i= 0
i= 1
i= 2
i= 9
i= 8

从输出结果可以看出,尽管for循环每次都会调用once.Do()方法,但是函数onceBody()却只会被执行一次。

参考文献

[1]Go语言——sync.Once分析.简书 [2]Package sync.Go 编程语言官网

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年02月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.简介
  • 2.示例
  • 参考文献
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档