-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgopool.go
94 lines (81 loc) · 1.56 KB
/
gopool.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"time"
)
type Pool struct {
Queue chan func() error
RuntineNumber int
Total int
Result chan error
FinishCallback func()
}
//初始化
func (self *Pool) Init(runtineNumber int, total int) {
self.RuntineNumber = runtineNumber
self.Total = total
self.Queue = make(chan func() error, total)
self.Result = make(chan error, total)
}
func (self *Pool) Start() {
//开启 number 个goruntine
for i := 0; i < self.RuntineNumber; i++ {
go func() {
for {
task, ok := <-self.Queue
if !ok {
break
}
err := task()
self.Result <- err
}
}()
}
//获取每个任务的处理结果
for j := 0; j < self.RuntineNumber; j++ {
res, ok := <-self.Result
if !ok {
break
}
if res != nil {
fmt.Println(res)
}
}
//结束回调函数
if self.FinishCallback != nil {
self.FinishCallback()
}
}
//关闭
func (self *Pool) Stop() {
close(self.Queue)
close(self.Result)
}
func (self *Pool) AddTask(task func() error) {
self.Queue <- task
}
func (self *Pool) SetFinishCallback(fun func()) {
self.FinishCallback = fun
}
func main() {
var p Pool
url := []string{"11111", "22222", "33333", "444444", "55555", "66666", "77777", "88888", "999999"}
p.Init(9, len(url))
for i := range url {
u := url[i]
p.AddTask(func() error {
return Download(u)
})
}
p.SetFinishCallback(DownloadFinish)
p.Start()
p.Stop()
}
func Download(url string) error {
time.Sleep(1 * time.Second)
fmt.Println("Download " + url)
return nil
}
func DownloadFinish() {
fmt.Println("Download finsh")
}