- Waiting for Goroutines with a WaitGroup
- Error Management with Error Groups
- Data Races
- Synchronizing Access with a Mutex
- Performing Tasks Only Once
- Summary
Performing Tasks Only Once
There are many times when you want to perform a task only once. For example, you might want to create a database connection only once and then use it to perform a number of queries. You can use the sync.Once23 type to do this.
As you can see from the documentation in Listing 13.43, the use of sync.Once is very simple. You just need to create a variable of type sync.Once and then call the sync.Once.Do24 method with a function that you want to run only once.
Listing 13.43 The sync.Once Type
$ go doc -all sync.Once package sync // import "sync" type Once struct { // Has unexported fields. } Once is an object that will perform exactly one action. A Once must not be copied after first use. func (o *Once) Do(f func()) Do calls the function f if and only if Do is being called for the first time for this instance of Once. In other words, given var once Once if once.Do(f) is called multiple times, only the first call will invoke f, even if f has a different value in each invocation. A new instance of Once is required for each function to execute. Do is intended for initialization that must be run exactly once. Since f is niladic, it may be necessary to use a function literal to capture the arguments to a function to be invoked by Do: config.once.Do(func() { config.init(filename) }) Because no call to Do returns until the one call to f returns, if f causes Do to be called, it will deadlock. If f panics, Do considers it to have returned; future calls of Do return without calling f.
Go Version: go1.19
The Problem
Often we want to use sync.Once to perform some heavy, expensive tasks only once.
Consider Listing 13.44. The Build function can be called many times, but we only want it to run once because it takes some time to complete.
Listing 13.44 The Build Method Is Slow and Should Be Called Only Once
type Builder struct { Built bool } func (b *Builder) Build() error { fmt.Print("building...") time.Sleep(10 * time.Millisecond) fmt.Println("built") b.Built = true // validate the message if !b.Built { return fmt.Errorf("expected builder to be built") } // return the b.msg and the error variable return nil }
As you can see from the test output, Listing 13.45, every call to the Build function takes a long time to complete, and each call performs the same task.
Listing 13.45 Output Confirming the Build Function Runs Every Time It Is Called
func Test_Once(t *testing.T) { t.Parallel() b := &Builder{} for i := 0; i < 5; i++ { err := b.Build() if err != nil { t.Fatal(err) } fmt.Println("builder built") if !b.Built { t.Fatal("expected builder to be built") } } }
$ go test -v === RUN Test_Once === PAUSE Test_Once === CONT Test_Once building...built builder built building...built builder built building...built builder built building...built builder built building...built builder built --- PASS: Test_Once (0.05s) PASS ok demo 0.265s
Go Version: go1.19
Implementing Once
As shown in Listing 13.46, you can use the sync.Once type inside the Build function to ensure that the expensive task is only performed once.
Listing 13.46 Using sync.Once to Run a Function Once
type Builder struct { Built bool once sync.Once } func (b *Builder) Build() error { var err error b.once.Do(func() { fmt.Print("building...") time.Sleep(10 * time.Millisecond) fmt.Println("built") b.Built = true // validate the message if !b.Built { err = fmt.Errorf("expected builder to be built") } }) // return the b.msg and the error variable return err }
As you can see from the test output, Listing 13.47, the Build function now performs the expensive task only once, and subsequent calls to the function are very fast.
Listing 13.47 Output Confirming the Build Function Runs Only Once
$ go test -v === RUN Test_Once === PAUSE Test_Once === CONT Test_Once building...built builder built builder built builder built builder built builder built --- PASS: Test_Once (0.01s) PASS ok demo 0.248s
Go Version: go1.19
Closing Channels with Once
The sync.Once type is useful for closing channels. When you want to close a channel, you need to ensure that the channel is closed only once. If you try to close the channel more than once, you get a panic, and the program crashes.
Consider the example in Listing 13.48. The Quit method on the Manager is in charge of closing the quit channel when the Manager is no longer needed.
Listing 13.48 If Called Repeatedly, the Quit Function Panics and Closes an Already-Closed Channel
type Manager struct { quit chan struct{} } func (m *Manager) Quit() { fmt.Println("closing quit channel") close(m.quit) }
If, however, the Quit method is called more than once, we are trying to close the channel more than once. We get a panic, and the program crashes.
As you can see in Listing 13.49, the tests failed as a result of trying to close the channel more than once and caused a panic.
Listing 13.49 Panicking When Trying to Close a Channel Multiple Times
func Test_Closing_Channels(t *testing.T) { t.Parallel() func() { // defer a function to catch the panic defer func() { // recover the panic if r := recover(); r != nil { // mark the test as a failure t.Fatal(r) } }() m := &Manager{ quit: make(chan struct{}), } // close the manager's quit channel m.Quit() // try to close the manager's quit channel again // this will panic m.Quit() }() }
$ go test -v === RUN Test_Closing_Channels === PAUSE Test_Closing_Channels === CONT Test_Closing_Channels closing quit channel closing quit channel demo_test.go:31: close of closed channel --- FAIL: Test_Closing_Channels (0.00s) FAIL exit status 1 FAIL demo 0.667s
Go Version: go1.19
In Listing 13.50, we use the sync.Once type to ensure that the Quit method, regardless of how many times it is called, only closes the channel once.
Listing 13.50 Using sync.Once to Close a Channel Only Once
type Manager struct { quit chan struct{} once sync.Once } func (m *Manager) Quit() { // close the manager's quit channel // this will only close the channel once m.once.Do(func() { fmt.Println("closing quit channel") close(m.quit) }) }
As you can see from the test output, Listing 13.51, the Quit method now closes the channel only once, and subsequent calls to the Quit method have no effect.
Listing 13.51 Output Confirming the Quit Method Closes the Channel Only Once
func Test_Closing_Channels(t *testing.T) { t.Parallel() m := &Manager{ quit: make(chan struct{}), } // close the manager's quit channel m.Quit() // try to close the manager's quit channel again // this will now have no effect m.Quit() }
$ go test -v === RUN Test_Closing_Channels === PAUSE Test_Closing_Channels === CONT Test_Closing_Channels closing quit channel --- PASS: Test_Closing_Channels (0.00s) PASS ok demo 0.523s
Go Version: go1.19