The dRuby Book

Chapter 5
Multithreading

In many systems, each thread shares the same memory address space. Systems can switch the flow of control, but they can’t switch memory space. So, threads tend to have less overhead and are often called lightweight processes.

With multithreading, you can easily write applications that handle multiple events, such as a network or GUI application. However, multithreading causes problems that don’t happen in single-threaded mode.

dRuby-based systems are often composed of multiple processes. When serving as a server, dRuby has no idea when clients will call the server methods. This situation is similar to what happens when programming in a multithreaded environment. In this chapter, we’ll learn about multithreading in Ruby, communication between threads, and how to apply these techniques when programming in dRuby.

Before you start this chapter, keep in mind that multithreading is a difficult topic in general; don’t be surprised if you feel overwhelmed by the number of topics covered in this chapter. Feel free to skip whenever you like. However, do read Section 5.4, Passing Objects via Queue to understand how to use Queue to communicate in a multithreaded environment, because we’ll compare Queue with other concepts in Chapter 6, Coordinating Processes Using Rinda and Chapter 9, Drip: A Stream-Based Storage System.