-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.go
More file actions
82 lines (72 loc) · 1.52 KB
/
worker.go
File metadata and controls
82 lines (72 loc) · 1.52 KB
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
package async
// Goroutine safe
type Worker struct {
closeChan chan bool
chanJob chan Job
chanRet chan Job
}
// Create a goroutine safe job worker
func NewWorker(chanSize int) *Worker {
mgr := &Worker{
closeChan: make(chan bool, 0),
chanJob: make(chan Job, chanSize),
chanRet: make(chan Job, chanSize),
}
go mgr.work()
return mgr
}
func (mgr *Worker) work() {
for {
select {
case <- mgr.closeChan:
return
case job := <- mgr.chanJob:
job.DoIt()
mgr.chanRet <- job
case ret := <- mgr.chanRet:
ret.Cb()
}
}
}
func (mgr *Worker) Dispose() {
mgr.closeChan <- true
}
func (mgr *Worker) AddJob(job Job) {
mgr.chanJob <- job
}
// Asynchronous call without returns
func (mgr *Worker) AsynCall0(f func([]interface{}), cb func(), args ...interface{}) {
job := &Job0{
args: args,
cb: cb,
f: f,
}
mgr.AddJob(job)
}
// Asynchronous call with a error return
func (mgr *Worker) AsynCall1(f func([]interface{}) error, cb func(error), args ...interface{}) {
job := &Job1{
args: args,
cb: cb,
f: f,
}
mgr.AddJob(job)
}
// Asynchronous call with two returns
func (mgr *Worker) AsynCall2(f func([]interface{}) (interface{},error), cb func(interface{},error), args ...interface{}) {
job := &Job2{
args: args,
cb: cb,
f: f,
}
mgr.AddJob(job)
}
// Asynchronous call with n returns
func (mgr *Worker) AsynCallN(f func([]interface{}) ([]interface{},error), cb func([]interface{},error), args ...interface{}) {
job := &JobN{
args: args,
cb: cb,
f: f,
}
mgr.AddJob(job)
}