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

评论 3

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    Your article helped me a lot, is there any more related content? Thanks!

    Binance推荐奖金1个月前 (03-17)回复
  2. #2

    I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://accounts.binance.info/si-LK/register?ref=LBF8F65G

    binance3周前 (04-04)回复
  3. #3

    Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.info/register?ref=JW3W4Y3A

    Binance推荐码3周前 (04-09)回复

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

支付宝扫一扫打赏

微信扫一扫打赏