I have an assignment where I have 2 numbers (a and b) and a count (n). I need to first generate random numbers that will be the time each thread will sleep for. Then, each thread calculates the sum, difference, product and division (respectively) of a and b and repeat that n times. For example:
a = 10
b = 2
n = 2
SUM: 12
DIFFERENCE: 8
PRODUCT: 20
DIVISION: 5
SUM: 12
DIFFERENCE: 8
PRODUCT: 20
DIVISION: 5
and in between each line, the program sleeps for some seconds. The order must be sum, difference, product and division. I can't use queues or kill/spawn threads repeatedly. My first thought was to use 4 conditional variables to dictate the order the threads need to run. I came up with this:
mutex = Mutex.new
resources = Array.new(4) { ConditionVariable.new }
t1 = Thread.new do
mutex.synchronize do
puts "Thread 1"
sleep(3)
resources[0].signal
end
end
t2 = Thread.new do
mutex.synchronize do
resources[0].wait(mutex)
puts "Thread 2"
sleep(3)
resources[1].signal
end
end
t3 = Thread.new do
mutex.synchronize do
resources[1].wait(mutex)
puts "Thread 3"
sleep(3)
resources[2].signal
end
end
t4 = Thread.new do
mutex.synchronize do
resources[2].wait(mutex)
puts "Thread 4"
sleep(3)
end
end
t1.join
t2.join
t3.join
t4.join
but I'm getting this deadlock error: main.rb:39:in 'join': No live threads left. Deadlock? (fatal)
Could this approach work? What should I do to fix it? Are there any other better approaches that could work?