Guest User

go sync.Pool

a guest
Feb 12th, 2016
650
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "math/rand"
  5.     "os"
  6.     "os/signal"
  7.     "sync"
  8. )
  9.  
  10. const count = 1000
  11.  
  12. var content = []byte(`
  13. The main use of the gc debug data is to record the size
  14. of the live objects on the heap, however this doesn’t
  15. reveal the total size of the heap, nor what percentage
  16. of the heap the live set represents. For that we need
  17. to add the debugging information from the scavenger.
  18. `)
  19.  
  20. const maxCap = 1024
  21.  
  22. type NoPool struct{}
  23.  
  24. func (_ NoPool) GetBytes() (b []byte) { return }
  25. func (_ NoPool) PutBytes(b []byte)    { /* nothing  */ }
  26. func (n NoPool) Process() {
  27.     b := n.GetBytes()
  28.     c := rand.Int31n(6) + 1
  29.     for i := int32(0); i < c; i++ {
  30.         b = append(b, content...)
  31.     }
  32.     n.PutBytes(b)
  33. }
  34.  
  35. type WithPool struct{}
  36.  
  37. var bytesPool = sync.Pool{}
  38.  
  39. func (_ WithPool) GetBytes() (b []byte) {
  40.     ifc := bytesPool.Get()
  41.     if ifc != nil {
  42.         b = ifc.([]byte)
  43.     }
  44.     return
  45. }
  46.  
  47. func (_ WithPool) PutBytes(b []byte) {
  48.     if cap(b) > maxCap {
  49.         return
  50.     }
  51.     b = b[:0]
  52.     bytesPool.Put(b)
  53. }
  54.  
  55. func (n WithPool) Process() {
  56.     b := n.GetBytes()
  57.     c := rand.Int31n(3) + 1
  58.     for i := int32(0); i < c; i++ {
  59.         b = append(b, content...)
  60.     }
  61.     n.PutBytes(b)
  62. }
  63.  
  64. type Processor interface {
  65.     Process()
  66. }
  67.  
  68. func main() {
  69.     var p Processor
  70.     if len(os.Args) >= 2 && os.Args[1] == "on" {
  71.         os.Stdout.WriteString("use pool\n")
  72.         p = WithPool{}
  73.     } else {
  74.         os.Stdout.WriteString("without pool\n")
  75.         p = NoPool{}
  76.     }
  77.     shut := make(chan struct{})
  78.     wg := new(sync.WaitGroup)
  79.     wg.Add(count)
  80.     for i := 0; i < count; i++ {
  81.         go func() {
  82.             defer wg.Done()
  83.             for {
  84.                 select {
  85.                 case <-shut:
  86.                     return
  87.                 default:
  88.                 }
  89.                 p.Process()
  90.             }
  91.         }()
  92.     }
  93.     c := make(chan os.Signal, 1)
  94.     signal.Notify(c, os.Interrupt)
  95.     <-c
  96.     os.Stdout.WriteString("interrupt\n")
  97.     close(shut)
  98.     wg.Wait()
  99. }
RAW Paste Data