Created
January 17, 2018 03:35
-
-
Save jsgoller1/ec845d91191b225679666575ed837e11 to your computer and use it in GitHub Desktop.
pools example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
func main() { | |
var numCalcsCreated int | |
calcPool := &sync.Pool{ | |
New: func() interface{} { | |
numCalcsCreated++ | |
mem := make([]byte, 1024) | |
return &mem | |
}, | |
} | |
calcPool.Put(calcPool.New()) | |
calcPool.Put(calcPool.New()) | |
calcPool.Put(calcPool.New()) | |
calcPool.Put(calcPool.New()) | |
const numWorkers = 1024 * 1024 | |
var wg sync.WaitGroup | |
wg.Add(numWorkers) | |
for i := numWorkers; i > 0; i-- { | |
go func() { | |
defer wg.Done() | |
mem := calcPool.Get().(*[]byte) | |
defer calcPool.Put(mem) | |
}() | |
} | |
wg.Wait() | |
fmt.Printf("%d calcs were created\n.", numCalcsCreated) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment