zoukankan      html  css  js  c++  java
  • Golang获取单实例

    Golang获取单实例

    方法一:

    import "sync"
    import "sync/atomic"
    
    var initialized uint32
    ... // 此处省略
    
    func GetInstance() *singleton {
    
        if atomic.LoadUInt32(&initialized) == 1 {  // 原子操作 
    		    return instance
    	  }
    
        mu.Lock()
        defer mu.Unlock()
    
        if initialized == 0 {
             instance = &singleton{}
             atomic.StoreUint32(&initialized, 1)
        }
    
        return instance
    }
    

    方法二:

    package singleton
    
    import (
        "sync"
    )
    
    type singleton struct {}
    
    var instance *singleton
    var once sync.Once
    
    func GetInstance() *singleton {
        once.Do(func() {
            instance = &singleton{}
        })
        return instance
    }
    

    说明:
    sync.Once的操作原子性,可以查看源码

    // Once is an object that will perform exactly one action.
    type Once struct {
    	// done indicates whether the action has been performed.
    	// It is first in the struct because it is used in the hot path.
    	// The hot path is inlined at every call site.
    	// Placing done first allows more compact instructions on some architectures (amd64/x86),
    	// and fewer instructions (to calculate offset) on other architectures.
    	done uint32
    	m    Mutex
    }
    
    func (o *Once) Do(f func()) {
    	if atomic.LoadUint32(&o.done) == 0 { // check
    		// Outlined slow-path to allow inlining of the fast-path.
    		o.doSlow(f)
    	}
    }
    
    func (o *Once) doSlow(f func()) {
    	o.m.Lock()                          // lock
    	defer o.m.Unlock()
    	
    	if o.done == 0 {                    // check
    		defer atomic.StoreUint32(&o.done, 1)
    		f()
    	}
    }
    

    相关链接

    go-singleton

    【励志篇】: 古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
  • 相关阅读:
    QML使用动画连续非线性改变int的取值
    QML粒子系统
    QML获取当前时间
    QML与C++混合编程
    QMLBinding
    QML图形渲染QtGraphicalEffects
    [九度][何海涛] 数组中只出现一次的数字
    [九度][何海涛] 扑克牌顺子
    [九度][何海涛] 最大子向量和
    [九度][何海涛] Move!Move!!Move!!!
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/14461824.html
Copyright © 2011-2022 走看看