优化重载服务的另一种思路

一个重载服务, 有很多优化思路, 缓存, 并行化都是不错的思路.
这里提供另外的一种思路: 提前生产开销大的对象.

package main  

import "time"  

type BufferProducer struct {  
   needProduct func() bool  
  product func()  
   producerNum uint  
}  

func New(needProduct func() bool,  
  product func(),  
  producerNum uint) (bp *BufferProducer) {  
   bp = &BufferProducer{  
      needProduct: needProduct,  
  product:     product,  
  producerNum: producerNum,  
  }  
   bp.Run()  
   return  
}  

func (bp *BufferProducer) Run() {  
   var f func()  
   f = func() {  
      defer func() {  
         go f()  
      }()  
      for {  
         if bp.needProduct() {  
            bp.product()  
         } else {  
            time.Sleep(100 \* time.Millisecond)  
         }  
      }  
   }  
   for i := uint(0); i < bp.producerNum; i\+\+ {  
      go f()  
   }  
}  
func (bp *BufferProducer) Stop() {  

}  

func main() {  
   qsize := int(100)  
   q := make(chan string, qsize)  
   bp := New(func() bool {  
      return len(q) < qsize/2  
  }, func() {  
      select {  
      case q <\- "item":  
         println("qsize:", qsize, "len q", len(q))  
      }  
   }, 10)  
   for {  
      println("qsize:", qsize, "len q", len(q))  
      _ = <-q  

  }  

   bp.Stop()  
}