Puppollo
2/14/2018 - 3:33 PM

worker pool

package main

import (
	"math/rand"
	"time"
	"fmt"
)

type (
	worker struct {
		id      int
		handled int
	}
)

func (w *worker) handle(input int) string {
	time.Sleep(time.Duration(w.id+1) * time.Second)
	w.handled++
	return fmt.Sprint(input, " test")
}

const poolSize = 10

func main() {
	rand.Seed(time.Now().Unix())

	pool := make(chan worker, poolSize)
	// pool worker init
	for i := 0; i < poolSize; i++ {
		pool <- worker{id: i}
	}

	go func() {
		for {
			input := rand.Intn(10)
			print("input:", input, " ")
			worker := <-pool // wait for worker
			go func() {
				fmt.Printf("result: %s, worker: %d, handled: %d\n", worker.handle(input), worker.id, worker.handled)
				pool <- worker // put worker back to pool
			}()

		}
	}()
	fmt.Scanln()
	close(pool)
}