Threads, Fibers, and Continuations

This section introduces threads, which are Ruby’s control structure for concurrent execution, and also two more esoteric control structures, called fibers and continuations.

Threads for Concurrency

A thread of execution is a sequence of Ruby statements that run (or appear to run) in parallel with the main sequence of statements that the interpreter is running. Threads are represented by Thread objects, but they can also be thought of as control structures for concurrency. Concurrent programming in Ruby is covered in detail in Threads and Concurrency. This section is just a simple overview that shows how to create threads.

Ruby’s use of blocks makes it very easy to create new threads. Simply call and associate a block with it. A new thread of execution will be created and will start running the code in the block. Meanwhile, the original thread will return from the call and will continue with the following statement. The newly created thread will exit when the block exits. The return value of the block becomes available through the value method of the Thread object. (If you call this method before the thread has completed, the caller will block until the thread returns a value.)

The following code shows how you might use threads to read the contents of multiple files in parallel:

# This method expects an array of filenames. # It returns an array of strings holding the content of the named files. # The method creates one thread for ...

Get The Ruby Programming Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.