Running a code block only once
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.
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", "Anton", "Yo"} type Source struct { m *sync.Mutex o *sync.Once data []interface{} } func (s *Source) Pop() (interface{}, error) { s.m.Lock() defer s.m.Unlock() s.o.Do(func() { s.data = names fmt.Println("Data has been loaded.") }) if...