-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool.go
More file actions
54 lines (47 loc) · 1.07 KB
/
Copy pathpool.go
File metadata and controls
54 lines (47 loc) · 1.07 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
// pool.go
package main
import (
"log"
)
// Job 表示一个需要被执行的任务
type Job struct {
Task Task
}
// WorkerPool 维护一个任务通道和工作协程池
type WorkerPool struct {
JobQueue chan Job
quit chan bool
}
// NewWorkerPool 创建一个新的工作池
func NewWorkerPool(maxWorkers int) *WorkerPool {
pool := &WorkerPool{
JobQueue: make(chan Job),
quit: make(chan bool),
}
for i := 0; i < maxWorkers; i++ {
go func(workerID int) {
for {
select {
case job := <-pool.JobQueue:
log.Printf("Worker %d: started job %s\n", workerID, job.Task.SourceID)
ProcessTask(&job.Task)
log.Printf("Worker %d: finished job %s\n", workerID, job.Task.SourceID)
case <-pool.quit:
log.Printf("Worker %d: stopping\n", workerID)
return
}
}
}(i + 1)
}
return pool
}
// Submit 提交一个新任务到工作池
func (p *WorkerPool) Submit(job Job) {
p.JobQueue <- job
}
// Stop 停止工作池
func (p *WorkerPool) Stop() {
go func() {
close(p.quit)
}()
}