O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Open the console and create the folder chapter10/recipe04.
  2. Navigate to the directory.
  3. 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 main() {          wg := &sync.WaitGroup{}          wg.Add(10)          for i := 0; i < 10; i++ {            go func(idx int) {              // This code block is done only once              w := pool.Get().(*Worker)              fmt.Println("Got worker ID: " + w.String())              time.Sleep(time.Second)              pool.Put(w)              wg.Done()            }(i)          }          wg.Wait()        }
  1. Execute the code by go run pool.go.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required