Go 工作线程池
在提供的例子中,很多地方都引用了这个例子Go 工作线程池,go,threadpool,channel,worker,Go,Threadpool,Channel,Worker,在提供的例子中,很多地方都引用了这个例子 func (d *Dispatcher) dispatch() { for { select { case job := <-JobQueue: // a job request has been received go func(job Job) { // try to obtain a worker job channel that is available.
func (d *Dispatcher) dispatch() {
for {
select {
case job := <-JobQueue:
// a job request has been received
go func(job Job) {
// try to obtain a worker job channel that is available.
// this will block until a worker is idle
jobChannel := <-d.WorkerPool
// dispatch the job to the worker job channel
jobChannel <- job
}(job)
}
}
}
如果你仔细阅读工人守则,你会注意到
w.WorkerPool <- w.JobChannel
w.WorkerPool啊。我知道我错过了什么。感谢您的意见!这似乎有点复杂(我确信它工作得很好)。有没有更好更直接的方法来实现工作线程池?坦率地说,我找不到更直接的方法。但是,示例中的实现实际上是一种“Go”方式
w.WorkerPool <- w.JobChannel
func (w Worker) Start() {
go func() {
for {
// register the current worker into the worker queue.
w.WorkerPool <- w.JobChannel
select {
case job := <-w.JobChannel:
// we have received a work request.
if err := job.Payload.UploadToS3(); err != nil {
log.Errorf("Error uploading to S3: %s", err.Error())
}
case <-w.quit:
// we have received a signal to stop
return
}
}
}()
}