Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "math/rand"
- "os"
- "os/signal"
- "sync"
- )
- const count = 1000
- var content = []byte(`
- The main use of the gc debug data is to record the size
- of the live objects on the heap, however this doesn’t
- reveal the total size of the heap, nor what percentage
- of the heap the live set represents. For that we need
- to add the debugging information from the scavenger.
- `)
- const maxCap = 1024
- type NoPool struct{}
- func (_ NoPool) GetBytes() (b []byte) { return }
- func (_ NoPool) PutBytes(b []byte) { /* nothing */ }
- func (n NoPool) Process() {
- b := n.GetBytes()
- c := rand.Int31n(6) + 1
- for i := int32(0); i < c; i++ {
- b = append(b, content...)
- }
- n.PutBytes(b)
- }
- type WithPool struct{}
- var bytesPool = sync.Pool{}
- func (_ WithPool) GetBytes() (b []byte) {
- ifc := bytesPool.Get()
- if ifc != nil {
- b = ifc.([]byte)
- }
- return
- }
- func (_ WithPool) PutBytes(b []byte) {
- if cap(b) > maxCap {
- return
- }
- b = b[:0]
- bytesPool.Put(b)
- }
- func (n WithPool) Process() {
- b := n.GetBytes()
- c := rand.Int31n(3) + 1
- for i := int32(0); i < c; i++ {
- b = append(b, content...)
- }
- n.PutBytes(b)
- }
- type Processor interface {
- Process()
- }
- func main() {
- var p Processor
- if len(os.Args) >= 2 && os.Args[1] == "on" {
- os.Stdout.WriteString("use pool\n")
- p = WithPool{}
- } else {
- os.Stdout.WriteString("without pool\n")
- p = NoPool{}
- }
- shut := make(chan struct{})
- wg := new(sync.WaitGroup)
- wg.Add(count)
- for i := 0; i < count; i++ {
- go func() {
- defer wg.Done()
- for {
- select {
- case <-shut:
- return
- default:
- }
- p.Process()
- }
- }()
- }
- c := make(chan os.Signal, 1)
- signal.Notify(c, os.Interrupt)
- <-c
- os.Stdout.WriteString("interrupt\n")
- close(shut)
- wg.Wait()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement