[go] using channel to realize simple work pool

Time:2021-2-6

Start a fixed number of goroutines first. Each goroutine is getting data from the channel. If the channel is empty, it will block and wait there
Pass a car type in channel, which is mainly responsible for specific tasks
In other words, the channel is the transportation channel. A car is delivered on this channel. When a car comes, it will handle the work of the car. If there is no car coming, these workers will wait there

 

package main

import (
    "log"
    "sync"
    "time"
)

type Pool struct {
    workerNum int
    road      chan *Car
    wg        sync.WaitGroup
}

//Initialize this object
func NewPool(wn int) *Pool {
    return &Pool{workerNum: wn, road: make(chan *Car)}
}

//Add specific tasks to channel
func (p *Pool) AddCar(f *Car) {
    p.road