Bounded Goroutine Pool Worker

Run tasks in a bounded goroutine pool with a job channel for controlled concurrency.

GoData Fetching

Code

gosnippet
19 lines
package main
import ("sync")
type Pool struct {
    jobs chan func()
    wg sync.WaitGroup
}
func NewPool(workers int) *Pool {
    p := &Pool{jobs: make(chan func(), workers*2)}
    for i := 0; i < workers; i++ {
        p.wg.Add(1)
        go func() {
            defer p.wg.Done()
            for job := range p.jobs { job() }
        }()
    }
    return p
}
func (p *Pool) Submit(job func()) { p.jobs <- job }
func (p *Pool) Shutdown() { close(p.jobs); p.wg.Wait() }

Inside the snippet

All of the logic lives in the functions NewPool, Submit and Shutdown.

The one repetition in this snippet is the loop for i := 0; i < workers; i++. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

Putting it to use

The primary signature is func NewPool(workers int) *Pool

NewPool is the public entry point; everything else in the file exists to support it.

Core lines

func (p *Pool) Submit(job func()) { p.jobs <- job }
func (p *Pool) Shutdown() { close(p.jobs); p.wg.Wait() }
p := &Pool{jobs: make(chan func(), workers*2)}

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `NewPool`, `Submit`, `Shutdown` at load time.