You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
package main
import (
"fmt""sync"
)
funcmain() {
variintpool:=&sync.Pool{
New: func() interface{} {
i++fmt.Println("Creating new instance", i)
returnstruct{}{}
},
}
// Populate the pool with 4 instances first.pool.Put(pool.New())
pool.Put(pool.New())
pool.Put(pool.New())
pool.Put(pool.New())
varwg sync.WaitGroupwg.Add(100)
fori:=0; i<100; i++ {
gofunc() {
deferwg.Done()
instance:=pool.Get()
deferpool.Put(instance)
// Do something quick here with the pool.// If the works takes longer to be returned and// another work is requesting item from the pool,// a new instance will be created instead,// hence defeating the purpose.// time.Sleep(1 * time.Second)
}()
}
wg.Wait()
fmt.Println("exiting")
}