-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathworker.go
99 lines (82 loc) · 1.48 KB
/
worker.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
95
96
97
98
99
package main
import "fmt"
//具体任务
type PayLoad struct {
Name string
}
func (p *PayLoad) GetData() error {
fmt.Printf("Hello Html. %s", p.Name)
return nil
}
//任务对象
type Job struct {
PayLoad PayLoad
}
var JobQueue chan Job
type Worker struct {
WorkerPool chan chan Job
JobChannel chan Job
quit chan bool
}
func NewWorker(workerPool chan chan Job) Worker {
return Worker{
WorkerPool: workerPool,
JobChannel: make(chan Job),
quit: make(chan bool),
}
}
func (w Worker) Start() {
go func() {
for {
w.WorkerPool <- w.JobChannel
select {
case job := <-w.JobChannel:
if err := job.PayLoad.GetData(); err != nil {
fmt.Println("get html is err.")
}
case <-w.quit:
fmt.Println("stop")
return
}
}
}()
}
func (w Worker) Stop() {
go func() {
w.quit <- true
}()
}
//调度器
type Dispatcher struct {
WorkerPool chan chan Job
maxWorkers int
}
func Prn() {
fmt.Println("daye")
}
func NewDispatcher(maxWorkers int) *Dispatcher {
return &Dispatcher{
WorkerPool: make(chan chan Job, maxWorkers),
maxWorkers: maxWorkers,
}
}
func (d *Dispatcher) Run() {
for i := 0; i < d.maxWorkers; i++ {
w := NewWorker(d.WorkerPool)
w.Start()
}
go d.dispatch()
}
func (d *Dispatcher) dispatch() {
for {
select {
case job := <-JobQueue:
go func(job Job) {
//试图获得一个工人工作通道可用。
jobChannel := <-d.WorkerPool
//分派工作的工人工作通道
jobChannel <- job
}(job)
}
}
}