Our example demonstrates how to implement a worker pool using F# asynchronous workflows and MailboxProcessor.
In this F# version:
We define a Job type and a WorkerMessage discriminated union to represent the messages our workers can receive.
The worker function uses a MailboxProcessor (also known as an agent) to receive and process jobs. It prints messages when starting and finishing jobs, and simulates work with a 1-second delay.
createWorkerPool creates a list of MailboxProcessor instances, each running a worker.
In the main function, we create a pool of 3 workers and send 5 jobs to them. We distribute the jobs among the workers using a simple round-robin approach.
After sending all jobs, we wait for them to complete (using a simple Thread.Sleep, though in a real application you’d want a more robust synchronization mechanism).
Finally, we send a Stop message to all workers to shut them down.
When you run this program, you’ll see output similar to the following:
This demonstrates the concurrent execution of jobs by multiple workers, similar to the original example. The program takes about 5 seconds to complete despite doing about 5 seconds of total work, because the 3 workers operate concurrently.