-
-
Save chsjiang/d0f4782407c7aa4fd1967cfc18726265 to your computer and use it in GitHub Desktop.
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
type Dispatcher struct { | |
// A pool of workers channels that are registered with the dispatcher | |
WorkerPool chan chan Job | |
} | |
func NewDispatcher(maxWorkers int) *Dispatcher { | |
pool := make(chan chan Job, maxWorkers) | |
return &Dispatcher{WorkerPool: pool} | |
} | |
func (d *Dispatcher) Run() { | |
// starting n number of workers | |
for i := 0; i < d.maxWorkers; i++ { | |
worker := NewWorker(d.pool) | |
worker.Start() | |
} | |
go d.dispatch() | |
} | |
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment