Go Once: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 17: Line 17:
}()
}()
</syntaxhighlight>
</syntaxhighlight>
<font color=darkkhaki>Is the function executed synchronously?</font>


=Methods=
=Methods=

Revision as of 22:34, 16 January 2024

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.