Worker Pools in Haskell
Our example demonstrates how to implement a worker pool using Haskell’s concurrency primitives.
In this example, we use Haskell’s Chan
type to create channels for communication between threads. The worker
function represents our worker, which receives jobs from the jobs
channel and sends results to the results
channel.
In the main
function:
- We create channels for jobs and results.
- We start 3 worker threads using
forkIO
. - We send 5 jobs to the
jobs
channel. - Finally, we collect all the results from the
results
channel.
This program demonstrates concurrent execution of tasks. Despite doing about 5 seconds of total work, the program should complete in about 2 seconds because there are 3 workers operating concurrently.
To run the program:
This output shows the 5 jobs being executed by various workers. Note that the exact order of execution may vary due to the concurrent nature of the program.
In Haskell, we use forkIO
to create lightweight threads, which are similar in concept to goroutines. The Chan
type provides a way for these threads to communicate, similar to channels in other languages.