Chapter 17. Threads

image with no caption

There may be times when your programs need to perform more than one action at a time. For example, maybe you want to do some disk operations and simultaneously display some feedback to the user. Or you might want to copy or upload some files “in the background” while still allowing the user to carry on with some other task “in the foreground.”

In Ruby, if you want to do more than one task at a time, you can run each task in its own thread. A thread is like a program within a program. It runs some particular piece of code independently of any other threads.

However, as you will see shortly, multiple threads may need to find ways of cooperating with each other so that, for example, they can share the same data and they don’t hog all the processing time available, thereby preventing other threads from running. When reading this chapter, you need to be aware that the behavior of threads in Ruby 1.9 and newer is substantially different from threads in 1.8 and older. I’ll explain why that is shortly.

Creating Threads

Threads can be created like any other object, using the new method. When you do this, you must pass to the thread a block containing the code you want the thread to run.

What follows is my first attempt at creating two threads, one of which should print four strings while the other prints ten numbers:

threads1.rb

# This is a simple threading example that, however,
# doesn't work as anticipated!

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

Thread.new{
    words.each{ |word| puts( word ) }
}

Thread.new{
    numbers.each{ |number| puts( number ) }
}

In all probability, when you run this, you may see nothing or, anyway, very little. It may display some strings and some numbers but not all of them and not in any easily predictable order. In the sample code in the archive, I’ve added a report of the time taken for the program to execute, which shows that the darn thing finishes before it has time to get started!

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

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