Application started.ab123c...uhh!Application stopped.
This article illustrates how to utilize Ruby’s features to perform parallel processing.
One way to perform processing in parallel is to utilize threads. If you are asking yourself when multi-threding is required, then take a look at the following list of applications that are utilizing this technique (or similar approaches) to handle many concurrent requests.
…and many, many more.
However, the following script is utilizing the threading interface of Ruby to start three additional threads in parallel. Just take a look at it and try to find out what is happening…
1234567891011121314151617181920212223242526272829 |
"""Source: www.linux-support.comAuthor: Mario ScondoDate: 2010-12-04 # Contents:# 1. Threading#""" def mymethod(variable) sleep 1 print '...uhh!' return variableend puts "Application started." x = Thread.new { sleep 0.2; print "1"; print "2"; print "3" }a = Thread.new { print "a"; print "b"; sleep 0.4; print "c" }b = Thread.new { mymethod('sabber') }x.join # wait for thread 1a.join # wait for thread 2b.join # wait for thread 3 putsputs "Application stopped." |
Line 20, 21: The first two threads are started by defining two blocks that are performing some outputs.
Line 22: This is an example how to start a thread by invoking a previously defined method.
All three threads are consisting of some statements to print strings and to fall to sleep for some time.
There are a number of additional features related to the threading interface. Please take a look a the follwing article to get an idea what is possible with Ruby.
When starting the script you will receive the following outputs:
Application started.ab123c...uhh!Application stopped.
Please note: the previous outputs may vary when executed on other machines. Because of the nature of program code working in parallel the outputs are a bit messy when no synchronization or queuing is performed!
Related articles:
Related resources: