Running Threads

Here is a simple fix to the thread-running problem. Right at the end of the code, add this:

threads2.rb

sleep( 5 )

This inserts a five-second delay. Now when you run the code again, you should see all the strings and all the numbers, albeit a bit jumbled up, like this:

hello1

2world
3

4goodbye

5mars
6
7
8
9

This is, in fact, exactly what you want since it shows that time is now being divided between the two threads. That’s why the words and numbers are jumbled, sometimes with even the carriage returns printed by the puts statements being mixed up, with either no carriage return or two at once being displayed. This happens because the threads are madly competing with one another for the available time—first one thread executes and displays a word, then the next thread executes and displays a number, then execution returns to the first thread, and so on, until the first thread ends (when all four words have been displayed), at which point the second thread can run without interruption.

Now compare this with the first version of the program. In that program, I created two threads, but just as Ruby was getting itself ready to run the code inside each thread—bam!—it arrived at the end of the program and shut everything down, including my two threads. So, in effect, the threads were killed off before they had time to do anything of any interest.

But when I add a call to sleep( 5 ) to insert a five-second delay, Ruby has plenty of time to run the threads before the program exits. There is just one problem with this technique—and it’s a big problem. Adding unnecessary delays to your programs in order to let threads run defeats the object of the exercise. The timer display now shows that the program takes all of five whole seconds to run, which is about 4.99 seconds or so longer than is strictly necessary! You’ll be learning more civilized ways of handling threads shortly. First, however, I need to say a few words about an important difference between threads in Ruby 1.8 and threads in Ruby 1.9.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.233