sinomoe / goworker

🦙 An implementation of worker pool pattern for concurrency control in golang.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

goworker

MIT

An implementation of worker pool pattern for concurrency control in golang.

Get started

import (
    "fmt"
    "time"
    
    "github.com/sinomoe/goworker/pool"
    "github.com/sinomoe/goworker/work"
)

// task A
func myWorkA(workerID int, work *work.DefaultWork) {
    fmt.Printf("Woker[%d] run work[%s]\n", workerID, work.Hash())
    time.Sleep(time.Second / 4)
}

// task B
func myWorkB(workerID int, work *work.DefaultWork) {
    fmt.Printf("Woker[%d] run work[%s]\n", workerID, work.Hash())
    time.Sleep(time.Second / 2)
}

func main() {
    // start pool 
    c := pool.StartDispatcher(4)
    
    // send task to collector
    c.Send(work.HandleFunc(myWorkA))
    c.Send(work.HandleFunc(myWorkB))
    
    // wait end
    c.End()
}

Further

  1. define your work type

    type Work struct {
        ID  int
        // ...
    }
  2. implement its Workable interface

    func (w *Work) Do(workerId int) {
        // ...
    }
  3. start a dispatcher and then returns the collector

    c := pool.StartDispatcher(4)
  4. send works to collector

    c.Send(&Work{
        ID: id,
        // ...
    })
  5. stop collector

    c.End()

for more, see example.go

About

🦙 An implementation of worker pool pattern for concurrency control in golang.

License:Other


Languages

Language:Go 100.0%