Skip to content

Instantly share code, notes, and snippets.

@jonbodner
Created January 22, 2018 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonbodner/c8c840f0530e215d20b81f35192ff060 to your computer and use it in GitHub Desktop.
Save jonbodner/c8c840f0530e215d20b81f35192ff060 to your computer and use it in GitHub Desktop.
type WorkPool struct {
work chan Runnable
shutdown chan struct{}
o sync.Once
}
type Runnable func()
func NewWorkPool(tasks int) *WorkPool {
work := make(chan Runnable, tasks)
shutdown := make(chan struct{})
for i := 0; i < tasks; i++ {
go func(i int) {
s := shutdown
for s != nil || len(work) > 0 {
select {
case r := <-work:
r()
case <-s:
fmt.Println("got shutdown in", i)
s = nil
}
}
fmt.Println("closing", i)
}(i)
}
return &WorkPool{
work: work,
shutdown: shutdown,
}
}
func (wp *WorkPool) SubmitWithTimeout(t time.Duration, r Runnable) error {
select {
case wp.work <- r:
case <-time.After(t):
return errors.New("Task submit timed out")
case <-wp.shutdown:
return errors.New("Work Pool shut down")
}
return nil
}
func (wp *WorkPool) Shutdown() {
wp.o.Do(func() {
fmt.Println("shutting down")
close(wp.shutdown)
})
}
func (wp *WorkPool) Empty() bool {
return len(wp.work) == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment