Waitgroups in OCaml
To wait for multiple threads to finish, we can use a semaphore in OCaml. Here’s an example implementation:
This OCaml code demonstrates the use of threads and semaphores to achieve similar functionality to the WaitGroup in the original example.
We define a worker
function that simulates some work by sleeping for a second and then printing a message.
In the main
function:
- We create a semaphore initialized to 0.
- We launch 5 threads, each running the
worker
function with a unique ID. - After each thread finishes its work, it releases the semaphore.
- In the main thread, we acquire the semaphore 5 times, effectively waiting for all worker threads to complete.
To run this program:
The order of workers starting up and finishing is likely to be different for each invocation.
Note that this approach uses OCaml’s native threads and semaphores. For more advanced use cases or better performance, you might want to consider using libraries like Lwt or Async for concurrent programming in OCaml.