Skip to content

Instantly share code, notes, and snippets.

@jbrodriguez
Created July 17, 2015 10:04
Show Gist options
  • Save jbrodriguez/a2e52696459af4ef8a9b to your computer and use it in GitHub Desktop.
Save jbrodriguez/a2e52696459af4ef8a9b to your computer and use it in GitHub Desktop.

Revisions

  1. jbrodriguez created this gist Jul 17, 2015.
    47 changes: 47 additions & 0 deletions pool.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    package pool

    type Task interface {
    Execute(id int)
    }

    type Pool struct {
    tasks chan Task
    kill chan bool
    }

    func NewPool(size, queue int) *Pool {
    pool := &Pool{
    tasks: make(chan Task, queue),
    kill: make(chan bool),
    }

    for i := 0; i < size; i++ {
    go pool.worker(i)
    }

    return pool
    }

    func (p *Pool) worker(id int) {
    for {
    select {
    case task, ok := <-p.tasks:
    if !ok {
    return
    }
    task.Execute(id)
    case <-p.kill:
    // should really kill it
    return
    }
    }
    }


    func (p *Pool) Close() {
    close(p.tasks)
    }

    func (p *Pool) Exec(task Task) {
    p.tasks <- task
    }