Waitgroups in Nim
Our first example demonstrates how to use a CountdownLatch
to wait for multiple threads to finish. This is similar to the concept of WaitGroups in other languages.
To run the program:
The order of workers starting up and finishing is likely to be different for each invocation.
In this Nim example, we use the threadpool
module to spawn threads, which is similar to launching goroutines. The CountdownLatch
from the locks
module serves a similar purpose to the WaitGroup in the original example.
We define a worker
procedure that simulates some work by sleeping for a second. In the main
procedure, we initialize a CountdownLatch
with a count of 5 (the number of workers we’ll spawn).
We then use a loop to spawn 5 threads, each running an anonymous procedure that calls worker
and then decrements the latch counter using countDown()
.
Finally, we call latch.wait()
, which blocks until the latch counter reaches zero, indicating that all workers have finished.
Note that Nim’s approach to concurrency is different from some other languages, and it doesn’t have a direct equivalent to goroutines. However, the threadpool
module provides a way to work with threads in a somewhat similar manner.