Go Once: Difference between revisions
Jump to navigation
Jump to search
Line 5: | Line 5: | ||
<code>Once</code> 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. | <code>Once</code> 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. | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
func init() { | |||
fmt.Println("initializing") | |||
} | |||
... | |||
var once sync.Once | var once sync.Once | ||
once.Do( | once.Do(init()) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Methods= | =Methods= | ||
==<tt>Do()</tt>== | ==<tt>Do()</tt>== | ||
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 19:59, 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 init() {
fmt.Println("initializing")
}
...
var once sync.Once
once.Do(init())
Methods
Do()
All invokers will block, except one, and they will be released after the one that does initialization finishes executing. The others will no execute.