Last active
December 13, 2016 07:31
-
-
Save jackypanster/1c961c044fe191d65ad2a14c5cb97eb4 to your computer and use it in GitHub Desktop.
thread pool pattern
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