Go Once: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 20: Line 20:
=Methods=
=Methods=
==<tt>Do()</tt>==
==<tt>Do()</tt>==
The only argument of <code>Do()</code> is a function value.
All invokers will block, except one, and they will be released after the one that does initialization finishes executing. The others will no execute.
All invokers will block, except one, and they will be released after the one that does initialization finishes executing. The others will no execute.

Revision as of 20:11, 5 September 2023

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)
  ...
}()

Methods

Do()

The only argument of Do() is a function value.

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