Pooling resources across multiple goroutines
Resource pooling is the traditional way to improve performance and save resources. Usually, it is worth pooling the resources with expensive initialization. The Go standard library provides the skeleton structure for a resource pool, which is considered to be safe for multiple goroutines access. This recipe describes how to use it.
How to do it...
- Open the console and create the folder
chapter10/recipe04
. - Navigate to the directory.
- Create the file
pool.go
with the following content:
package main import "sync" import "fmt" import "time" type Worker struct { id string } func (w *Worker) String() string { return w.id } var globalCounter = 0 var pool = sync.Pool{ New: func() interface{} { res := &Worker{fmt.Sprintf("%d", globalCounter)} globalCounter++ return res }, } func...