-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtaskpool.go
72 lines (59 loc) · 1.14 KB
/
taskpool.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
package foog
import (
"log"
)
type taskFn func(interface{})error
type taskEntity struct{
fn taskFn
data interface{}
done chan error
}
type TaskPool struct{
workerNum int
queue chan *taskEntity
}
func NewTaskPool(workerNum int, queueNum int)*TaskPool{
tp := &TaskPool{
workerNum: workerNum,
queue : make(chan *taskEntity, queueNum),
}
return tp
}
func (this *TaskPool)Start(){
for i := 0; i < this.workerNum; i++{
go this.runWorker(i+1)
}
}
func (this *TaskPool)AsyncPost(data interface{}, fn taskFn){
this.postRaw(data, nil, fn)
}
func (this *TaskPool)Post(data interface{}, fn taskFn)error{
return this.postRaw(data, make(chan error), fn)
}
func (this *TaskPool)postRaw(data interface{}, done chan error, fn taskFn)error{
var err error
if this.workerNum > 0{
this.queue <- &taskEntity{
fn: fn,
data: data,
done: done,
}
if done != nil{
err = <-done
}
}else{
err = fn(data)
log.Println("runat current co")
}
return err
}
func (this *TaskPool)runWorker(i int){
for{
task := <-this.queue
err := task.fn(task.data)
if task.done != nil{
task.done <- err
}
log.Println("runat taskpool co", i)
}
}