美文网首页
Go语言——sync.Once分析

Go语言——sync.Once分析

作者: 陈先生_9e91 | 来源:发表于2018-11-06 15:27 被阅读0次

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

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

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

相关文章

  • Go语言——sync.Once分析

    Go语言——sync.Once分析 sync.Once表示只执行一次函数。要做到这点,就需要两点: 计数器,统计函...

  • 深度剖析Golang sync.Once源码

    目录 什么是sync.Once 如何使用sync.Once 源码分析 什么是sync.Once Once 可以用来...

  • sync.Once

    sync.Once 的使用场景 sync.Once 是 Go 标准库提供的使函数只执行一次的实现,常应用于单例模式...

  • go 中的 sync.Once

    sync.Once 是 Go 标准库提供的使函数只执行一次的实现,常应用于单例模式,sync.Once 仅提供了一...

  • golang内存逃逸

    一篇很好的博客: Go 语言机制之栈与指针 Go 语言机制之逃逸分析 Go 语言机制之内存剖析 Go 语言机制之数...

  • golang 系列:sync.Once 讲解

    sync.Once 介绍 之前提到过 Go 的并发辅助对象:WaitGroup[https://mp.weixin...

  • Go - sync.Once

    设计目的 Once 常常用来初始化单例资源,或者并发访问只需初始化一次的共享资源,或者在测试的时候初始化一次测试资...

  • go语言开发工具分享

    google的go语言分析诊断工具 centos先安装gops gops —— Go 程序诊断分析工具[https...

  • Go 语言极速入门总结

    Go 语言使用 非常简单,是专门针对各种语言的痛点设计的!!!在前边的源码分析中,分析了 Go 1.11.1 的基...

  • go 语言进阶学习笔记(一)

    我先想分析一下现在有哪些公司使用go 语言,go语言在实际开发中有哪些使用场景,为什么要从其他语言转换成go语言。...

网友评论

      本文标题:Go语言——sync.Once分析

      本文链接:https://www.haomeiwen.com/subject/opeuxqtx.html