Last updated:
0 purchases
This Ruby code implements a simple producer-consumer model using threads and a thread-safe queue. The program simulates the production and consumption of items, demonstrating how multiple producers can generate items concurrently while multiple consumers process those items.
Key Components
id
) assigned during initialization.produce
method simulates work by sleeping for a random duration after producing each item.consume
method continuously attempts to pop items from the queue until no more items are available.nil
values are added to the queue to signal the consumers to stop.Threading and Synchronization
Thread
class to create and manage multiple threads for producers and consumers.Queue
class is used to ensure thread-safe operations when adding and removing items, preventing race conditions.Example Output
When executed, the program will produce output similar to the following:
Producer 0 produced item 0
Producer 1 produced item 10
Producer 2 produced item 20
Consumer 0 consumed item 0
Consumer 1 consumed item 10
All producers and consumers have finished.
This output demonstrates the interleaved execution of producers and consumers, showcasing the concurrent nature of the program.
This Ruby code effectively illustrates the producer-consumer problem using threads and a synchronized queue, providing a clear example of concurrent programming in Ruby. It highlights the importance of thread safety and synchronization when multiple threads interact with shared resources.
id
) assigned during initialization.produce
method simulates work by sleeping for a random duration after producing each item.consume
method continuously attempts to pop items from the queue until no more items are available.nil
values are added to the queue to signal the consInstall the latest version of Ruby
To get the best result possibe, use Visual Studio Code.
For personal and professional use. You cannot resell or redistribute these repositories in their original state.
There are no reviews.