..

一个golang的goroutine pool的简单实现

宗旨就是使用单个goroutine持续消费channel中的function对象。

package main

import (
	"time"
)

const BufferSize = 16
type Pool struct {
	ch   chan func()
	size int
}

func NewPool(size int)*Pool{
	p  := new(Pool)
	p.ch = make(chan func(),BufferSize)
	p.size = size
	return p
}

func (p *Pool)Start(){
	p.loop()
}
func (p *Pool)loop(){
	for i := 0; i < p.size ; i++{
		go func(ch chan func()){
			for{
				select {
				case f := <- ch:
					f()
				default:
					continue
				}
			}
		}(p.ch)
	}
}
func (p *Pool)Run(f func()){
	p.ch <- f
}

func main(){
	pool := NewPool(10)
	pool.loop()
	pool.Run(func(){
		println("Hello World")
	})
	time.Sleep(time.Duration(3)*time.Second)
}