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 | func initialization() { | ||
fmt.Println("initializing") | fmt.Println("initializing ...") | ||
} | } | ||
... | ... | ||
once.Do( | go func() { | ||
... | |||
once.Do(initialization) | |||
... | |||
}() | |||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 20:10, 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()
All invokers will block, except one, and they will be released after the one that does initialization finishes executing. The others will no execute.