一个golang的goroutine pool的简单实现

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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)
}