💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 示例 ### 概念示例 <details> <summary>main.go</summary> ``` package main import ( "fmt" "sync" ) var lock = sync.Mutex{} type single struct { } var singleInstance *single func getInstance() *single { if singleInstance == nil { lock.Lock() defer lock.Unlock() if singleInstance == nil { fmt.Println("Creating single instance now.") singleInstance = &single{} } else { fmt.Println("Single instance already created1.") } } else { fmt.Println("Single instance already created2.") } return singleInstance } func main() { for i := 0; i < 5; i++ { go getInstance() } fmt.Scanln() } ``` </details> <br /> 输出 ``` Creating single instance now. Single instance already created1. Single instance already created2. Single instance already created1. Single instance already created1. ``` ### 使用 init 函数 我们可以在`init`函数中创建单例实例。这仅适用于实例的早期初始化工作已经确定时。​`init`函数仅会在包中的每个文件里调用一次,所以我们可以确定其只会创建一个实例。 ### sync.Once [推荐] sync.Once仅会执行一次操作 <details> <summary>main.go</summary> ``` package main import ( "fmt" "sync" ) var once sync.Once type single struct { } var singleInstance *single func getInstance() *single { if singleInstance == nil { once.Do( func() { fmt.Println("Creating single instance now.") singleInstance = &single{} }) } else { fmt.Println("Single instance already created.") } return singleInstance } func main() { for i := 0; i < 5; i++ { go getInstance() } fmt.Scanln() } ``` </details> <br /> 输出 ``` Creating single instance now. Single instance already created. Single instance already created. Single instance already created. ```