In situations when multiple goroutines run the same code and there is a code block that initializes, for example, shared resource, the Go standard library offers the solution, which will be described further.
Running a code block only once
How to do it...
- Open the console and create the folder chapter10/recipe03.
- Navigate to the directory.
- Create the file once.go with the following content:
package main
import (
"fmt"
"sync"
)
var names = []interface{}{"Alan", "Joe", "Jack", "Ben",
"Ellen", "Lisa", "Carl", "Steve",
...