Waitgroups in Ruby
Our first example demonstrates the usage of a concept similar to WaitGroups in Ruby. We’ll use the Thread
class and a mutex to achieve similar functionality.
In this Ruby example, we’re using threads to perform concurrent work. Here’s a breakdown of what’s happening:
We define a
worker
function that simulates some work by sleeping for a second.We create a mutex and a counter to keep track of active threads.
We launch 5 threads, each running the
worker
function.For each thread, we increment a counter before it starts and decrement it when it finishes.
In the main thread, we wait until the counter reaches zero, indicating all threads have completed.
This approach mimics the behavior of WaitGroups in Go, allowing us to wait for multiple threads to finish before proceeding.
To run the program:
The order of workers starting up and finishing is likely to be different for each invocation.
Note that while this approach works, Ruby has other concurrency primitives that might be more idiomatic depending on your specific use case, such as the concurrent-ruby
gem which provides more advanced concurrency tools.