Search⌘ K
AI Features

Printing FooBar n Times

Explore how to synchronize two Ruby threads to print 'Foo' and 'Bar' alternately based on user input n. Understand the use of mutex and condition variables to control thread execution order and avoid race conditions.

We'll cover the following...

Problem

Suppose there are two threads t1 and t2. t1 prints Foo and t2 prints Bar. You are required to write a program which takes a user input n. Then the two threads print Foo and Bar alternately n number of times. The code for the class is as follows:

class PrintFooBar 
    
    def PrintFoo()
        for i in 1..n do
        print "Foo"    
        end  
    end
 
    def PrintBar() 
        for i in 1..n do      
        print "Bar"    
        end  
    end
end

The two threads will run sequentially. You have to ...