golang实现单例模式

本文介绍了如何在Go语言中使用sync.Once实现线程安全的单例模式。示例代码展示了GetInstance函数,确保singleton实例只被创建一次。sync.Once通过原子操作确保在并发环境下正确初始化单例,保证了线程安全。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

golang实现单例模式

go已经提供了实现单例模式的工具sync.Once

示例

借用sync.Once的一次性特点

import (
    "sync"
)

type singleton struct {
}

var _instance *singleton
var _once sync.Once

func GetInstance() *singleton {
	_once.Do(func() {
		instance = &singleton{}
	})
	return instance
}

once原理

用变量done的指针地址作为key,标记在atmoic中,同时借用atomic的原子特性, 达到线程安全的效果。

package sync

import (
	"sync/atomic"
)


type Once struct {
	done uint32
	m    Mutex
}

func (o *Once) Do(f func()) {

	if atomic.LoadUint32(&o.done) == 0 {
		// Outlined slow-path to allow inlining of the fast-path.
		o.doSlow(f)
	}
}

func (o *Once) doSlow(f func()) {
	o.m.Lock()
	defer o.m.Unlock()
	if o.done == 0 {
        //取done的索引地址作为key保存
		defer atomic.StoreUint32(&o.done, 1)
		f()
	}
}

佛說大乘無量壽莊嚴清淨平等覺經pdf
净土大经科注2014-doc
此生必看的科学实验-水知道答案
印光大师十念法(胡小林主讲第1集)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值