to be
a problem slover

go sync.Once by example

sync.Once ensure the anonymous function execute only once, and before execution finished, it will block all the other goroutines.

sync.Once is singleton pattern, it can be used to initialize config / singleton instance.

func TestSyncOnce(t *testing.T) {
    var once sync.Once
    for i:=0;i<=5;i++{
        go func(i int) {
            once.Do(func() {
                fmt.Println("inside once: ", i)
                time.Sleep(5 * time.Second)
            })
            fmt.Println(i)
        }(i)
    }
    time.Sleep(6 * time.Second)
}

result

inside once:  5
<sleep 5 seconds>
5
0
1
2
3
4

real world example

var (
    signer      types.Signer
    onlyOnce    sync.Once
)

func getSender(tx *types.Transaction) (common.Address, error) {
    onlyOnce.Do(func() {
        signer = types.LatestSignerForChainID(tx.ChainId())
    })
    return signer.Sender(tx)
}
赞(7) 打赏
欢迎转载,注明出处:刘世明的博客 » go sync.Once by example

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下作者

支付宝扫一扫打赏

微信扫一扫打赏