The dRuby Book

5.1 dRuby and Multithreading

Multithreading is vital in dRuby. In this section, we’ll take a look at the relationship between dRuby and multithreading.

Always in Multithreading Mode

dRuby generates threads by first having DRb.start_service generate a server thread that waits for method calls from other processes. Then, every time the server thread receives a method call from the client, the server generates a new thread that takes care of executing the method call.

While the server is handling other remote method calls, it creates a new thread and executes it when there’s a call from a client.

Let’s see how process A calls process B (see Figure 19, How remote method calls work).

images/d2drbsrv0.png

Figure 19. How remote method calls work
  ​there = DRbObject.new_with_uri('...')​
  ​there.foo()​

When there is a request to process B, then a server thread at DRbServer receives the request. DRbServer then creates a new method invocation and delegates the task to it in a separate thread. As soon as it gets delegated, the server thread comes back and prepares for the next method call (see Figure 20, Implementing a remote method call).

images/d2drbsrv.png

Figure 20. Implementing a remote method call

Thanks to this mechanism, dRuby can receive different calls and execute them while it’s in the middle of processing other calls. Let’s think about the following code:

  ​ary = DRbObject.new_with_uri(..)​
  ​ary.each do |x|​
  ​ x.foo()​
  ​end​

Because dRuby has no constraints—such as blocking other method calls while performing a method call—it doesn’t cause a deadlock when two processes call each other (see Figure 21, Two processes calling each other). This architecture enables you to call remote methods with block arguments.

images/d2yield.png

Figure 21. Two processes calling each other

The main goal of dRuby is to extend Ruby’s method invocation to a distributed environment. I implemented dRuby so that objects can call each other just as they do in normal Ruby scripts. For this reason, you have to pay particular attention to multithreading when using dRuby. Always bear in mind that the server script may receive method calls at any time.