// The implementaion of a simple goroutines pool with fixed capacity // By dicer 2/25/2021
package main
import ( "fmt" "time" )
// Define Task type Task struct{ fn func()error submitTime time.Time // Alternative property // #user // #taskID }
// Return a new task with a function argFn funcNewTask(argFn func()error) *Task { t := Task{ fn: argFn, submitTime: time.Now(), } return &t }
// Execute the fn of a Task func(t *Task)Execute() { t.fn() }
// Define Pool type Pool struct { TasksChan chan *Task JobsChan chan *Task Cap uint }
// Return a new pool with fixed capacity funcNewPool(capuint) *Pool { p := Pool{ TasksChan: make(chan *Task, cap), JobsChan: make(chan *Task, cap), Cap: cap, } return &p }
// Generate a worker entity used as a coroutine func(p *Pool)Worker(WorkerID int) { // take a task from JobsChan for t := range p.JobsChan { // execute this task t.Execute() // print info fmt.Printf("Worker %d has finished a task submited at %v.\n", WorkerID, t.submitTime) } }
// Run the pool with cap_size worker func(p *Pool)Run() {
for i := 0; uint(i) < p.Cap; i++ { go p.Worker(i) }
for { p.JobsChan <- <- p.TasksChan } fmt.Println("Debug") }
// Test the Pool funcmain() { t := NewTask(func()error { _, err := fmt.Println(time.Now()) return err })