Threading Model


Ruby Way
By Hal Fulton
Slots : 1.0
Table of Contents

Ruby threading is built-in by default; no compiler flag is needed. All threads run within a single interpreter instance, time-sliced within its process (similar to microthreads in Stackless Python). Such threading is generally not compatible with system-level threading, and it does not take advantage of multiprocessor systems.

Calling blocking I/O functions from within one thread will cause all threads to be blocked. There is no global interpreter lock available to help avoid this. Such situations require you to fork/exec, but note that forking from inside a thread currently causes all threads to be duplicated. In general, avoid mixing system forking with Ruby threading.

Nevertheless, threads are simple to use in Ruby. Just instantiate a thread object from the Thread class with an associated block of code.


 begin     i=0{  sleep 5; raise ThreadError }{  loop{  i+=1; puts i; sleep rand() }  }     t1.join; t2.join rescue ThreadError puts "Time's up!" end 

Notice that there is no need to subclass. Don't forget to join the thread instances to the main thread.

If you have Python code that uses daemon-based threads, you will not be able to convert it directly to Ruby's threads.

Ruby also has continuation objects, which are like a special form of thread. As such, they are interpreter-based and subject to some limitations.




The Ruby Way
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2000
Pages: 119
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: