Table of contents
1.
Introduction
2.
Go Worker Pools
3.
Example
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Go Worker Pools

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we are discussing Go Worker Pools, and we will be learning about the implementation of Go Worker Pools by example. 

Go Worker Pools

A design in which a set number of m workers (Go goroutines) work on n tasks in a work queue(Go channel) is known as a worker pool. The work is held in a queue until a worker completes their current task and moves on to the next.

Example

package main
import 
(
    "fmt"
    "time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
    for j:= range jobs{
        fmt.Println("worker", id, "started job", j)
        time.Sleep(time.Second)
        fmt.Println("worker", id, "finished job", j)
        results <- j * 2
    }
}
func main() {
    const numJobs = 5
        jobs := make(chan int, numJobs)
        results := make(chan int, numJobs)
    for w := 1; w <= 3; w++ {
            go worker(w, jobs, results)
        }
    for j := 1; j <= numJobs; j++ {
            jobs <- j
        }
        close(jobs)
    for a := 1; a <= numJobs; a++ {
            <-results
        }
}
You can also try this code with Online C Compiler
Run Code

Output

worker 3 started job 1
worker 1 started job 2
worker 2 started job 3
worker 3 finished job 1
worker 3 started job 4
worker 2 finished job 3
worker 2 started job 5
worker 1 finished job 2
worker 2 finished job 5
worker 3 finished job 4
You can also try this code with Online C Compiler
Run Code

The above example is for the implementation of Go Worker Pools.

FAQs

  1. What are Worker Pools? 
    Ans: A design in which a set number of m workers (Go goroutines) work on n tasks in a work queue is known as a worker pool (Go channel). The work is held in a queue until a worker completes his current task and moves on to the next.
     
  2. How many types of API of the worker pool? 
    Ans: The worker pool API is made up of two parts: a function called workerpool.pool that creates a worker pool and a function called worker pool. To make a worker, you must first make a worker.

Key Takeaways

In this article, we have extensively discussed Worker Pools and learned by example.

"We hope that this blog enhances your knowledge regarding Worker Pools, and if you would like to learn more, check out our articles on Library. You can learn about Channels and GoRoutines by visiting Concurrency in Go. Do upvote our blog to help other ninjas grow. Happy Coding!"

Live masterclass