-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix #1 Scheduler has deadlock on worker stop, if worker has not yet s…
…tarted execute
- Loading branch information
Showing
3 changed files
with
67 additions
and
63 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,50 +1,45 @@ | ||
package pool | ||
|
||
import "time" | ||
|
||
// 任务执行者 | ||
type worker struct { | ||
idle bool // worker是否空闲 | ||
end chan bool // worker是否停止 | ||
q Queue // worker接入的队列 | ||
jobConsumeQueue Queue // worker接入的队列 | ||
notifyChan chan worker | ||
} | ||
|
||
// 开工 | ||
func (w *worker) start() { | ||
go w.execute() | ||
} | ||
|
||
// 停工 | ||
func (w *worker) stop() { | ||
w.end <- true | ||
} | ||
|
||
// 循环执行任务 | ||
func (w *worker) execute() { | ||
c := time.NewTicker(time.Second).C | ||
killNextCycle := make(chan bool, 1) | ||
for { | ||
select { | ||
case job := <-w.q.poll(): | ||
w.idle = false | ||
case job := <-w.jobConsumeQueue.poll(): | ||
if nil != job.Run { | ||
job.Run(job.Args...) | ||
} | ||
case <-c: | ||
w.idle = true | ||
case <-w.end: | ||
case <-killNextCycle: | ||
w.notifyChan <- *w | ||
return | ||
} | ||
//situation when u are spawned but some other worker read your data | ||
//hence do not wait forever for data, if you dont have it now, | ||
//try to die in next cycle, cos select is random when all ready | ||
killNextCycle <- true | ||
} | ||
} | ||
|
||
// 初始化指定数量的worker, 并接入队列 | ||
func newWorkers(num int, q Queue) (ws []*worker) { | ||
func newWorkers(num int, q Queue) (workers chan worker) { | ||
workers = make(chan worker, num) | ||
for i := 0; i < num; i++ { | ||
ws = append(ws, &worker{ | ||
idle: true, | ||
end: make(chan bool), | ||
q: q, | ||
}) | ||
worker := worker{ | ||
jobConsumeQueue: q, | ||
notifyChan: workers, | ||
} | ||
workers <- worker | ||
} | ||
return | ||
} |