Go Once

From NovaOrdis Knowledge Base
Revision as of 22:34, 16 January 2024 by Ovidiu (talk | contribs) (→‎Overview)
Jump to navigation Jump to search

Internal

Overview

Once is a Go synchronization construct that is used when a piece of code must be executed only once. This is a useful idiom in initialization.

func initialization() {
  fmt.Println("initializing ...")
}

...

go func() {
  ...
  once.Do(initialization)
  ...
}()

Is the function executed synchronously?

Methods

Do()

The only argument of Do() is a function value, not a function invocation. Do() will use the function value to invoke the function, internally.

All invokers will block, except one, and they will be released after the one that does initialization finishes executing. The others will no execute.