Ensuring That a Thread Executes

Let’s return to the problem I had in the previous programs. Recall that I created two threads, but the program finished before either of them had a chance to run fully. I fixed this by inserting a fixed-length delay using the sleep method. Deliberately introducing gratuitous delays into your programs is not something you would want to do as a general rule. Fortunately, Ruby has a more civilized way of ensuring that a thread has time to execute. The join method forces the calling thread (for example, the main thread) to suspend its own execution (so it doesn’t just terminate the program) until the thread that calls join has completed:

join.rb

words = ["hello", "world", "goodbye", "mars" ] numbers = [1,2,3,4,5,6,7,8,9,10] ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.