An implementation of worker pool pattern for concurrency control in golang.
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()
}
-
define your work type
type Work struct { ID int // ... }
-
implement its Workable interface
func (w *Work) Do(workerId int) { // ... }
-
start a dispatcher and then returns the collector
c := pool.StartDispatcher(4)
-
send works to collector
c.Send(&Work{ ID: id, // ... })
-
stop collector
c.End()
for more, see example.go