Ordered Printing
Understand how to synchronize multiple Ruby threads to print output in a specific order using mutex locks and condition variables. This lesson guides you through implementing ordered printing with thread coordination, ensuring First, Second, and Third are printed sequentially regardless of thread execution order.
We'll cover the following...
Problem
Suppose there are three threads t1, t2 and t3. t1 prints First, t2 prints Second and t3 prints Third. The code for the class is as follows:
class OrderedPrinting
def printFirst()
puts "First"
end
def printSecond()
puts "Second"
end
def printThird()
puts "Third"
end
Thread t1 calls printFirst(), thread t2 calls printSecond(), and thread t3 calls printThird(). The threads can run in any order. You have to synchronize the threads so that the functions printFirst(), printSecond() and printThird() are executed in order.
The workflow of the program is shown below: