- 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 thesync.Once23type to do this.
As you can see from the documentation in Listing 13.43, the use ofsync.Onceis very simple. You just need to create a variable of typesync.Onceand then call thesync.Once.Do24method with a function that you want to run only once.
Listing 13.43 Thesync.OnceType
$ 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 firsttime 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 ofOnce is required for each function to execute. Do is intended for initialization that must be run exactly once. Since fis niladic, it may be necessary to use a function literal to capture thearguments 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 fcauses Do to be called, it will deadlock. If f panics, Do considers it to have returned; future calls of Do returnwithout calling f.
Go Version: go1.19
The Problem
Often we want to usesync.Onceto perform some heavy, expensive tasks only once.
Consider Listing 13.44. TheBuildfunction can be called many times, but we only want it to run once because it takes some time to complete.
Listing 13.44 TheBuildMethod Is Slow and Should Be Called Only Once
typeBuilderstruct{Builtbool}func(b*Builder)Build()error{fmt.Print("building...")time.Sleep(10*time.Millisecond)fmt.Println("built")b.Built=true// validate the messageif!b.Built{returnfmt.Errorf("expected builder to be built") }// return the b.msg and the error variablereturnnil}
As you can see from the test output, Listing 13.45, every call to theBuildfunction takes a long time to complete, and each call performs the same task.
Listing 13.45 Output Confirming theBuildFunction Runs Every Time It Is Called
funcTest_Once(t*testing.T) {t.Parallel()b:= &Builder{}fori:=0;i<5;i++ {err:=b.Build()iferr!=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 thesync.Oncetype inside theBuildfunction to ensure that the expensive task is only performed once.
Listing 13.46 Usingsync.Onceto Run a Function Once
typeBuilderstruct{Builtboolonce sync.Once}func(b*Builder)Build()error{varerrerrorb.once.Do(func() {fmt.Print("building...")time.Sleep(10*time.Millisecond)fmt.Println("built")b.Built=true// validate the messageif!b.Built{err=fmt.Errorf("expected builder to be built") } })// return the b.msg and the error variablereturnerr}
As you can see from the test output, Listing 13.47, theBuildfunction now performs the expensive task only once, and subsequent calls to the function are very fast.
Listing 13.47 Output Confirming theBuildFunction 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
Thesync.Oncetype 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. TheQuitmethod on theManageris in charge of closing thequitchannel when theManageris no longer needed.
Listing 13.48 If Called Repeatedly, theQuitFunction Panics and Closes an Already-Closed Channel
typeManagerstruct{quitchan struct{} }func(m*Manager)Quit() {fmt.Println("closing quit channel")close(m.quit) }
If, however, theQuitmethod 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
funcTest_Closing_Channels(t*testing.T) {t.Parallel()func() {// defer a function to catch the panicdefer func() {// recover the panicifr:=recover();r!=nil{// mark the test as a failuret.Fatal(r) } }()m:= &Manager{quit:make(chan struct{}), }// close the manager's quit channelm.Quit()// try to close the manager's quit channel again // this will panicm.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 thesync.Oncetype to ensure that theQuitmethod, regardless of how many times it is called, only closes the channel once.
Listing 13.50 Usingsync.Onceto Close a Channel Only Once
typeManagerstruct{quitchan struct{}once sync.Once}func(m*Manager)Quit() {// close the manager's quit channel // this will only close the channel oncem.once.Do(func() {fmt.Println("closing quit channel")close(m.quit) }) }
As you can see from the test output, Listing 13.51, theQuitmethod now closes the channel only once, and subsequent calls to theQuitmethod have no effect.
Listing 13.51 Output Confirming theQuitMethod Closes the Channel Only Once
funcTest_Closing_Channels(t*testing.T) {t.Parallel()m:= &Manager{quit:make(chan struct{}), }// close the manager's quit channelm.Quit()// try to close the manager's quit channel again // this will now have no effectm.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