SoFunction
Updated on 2025-04-07

Classic producer consumer problem code example using threads in Ruby


require "thread"
puts "ProAndCon"
  
queue =     #Use queue Queue to implement thread synchronization
  
producer = do
    do |i| 
sleep rand(i) # Let the thread sleep for a while
        queue << i 
        puts "#{i} produced"
    end
end
  
consumer = do
    do |i| 
        value =  
        sleep rand(i/2) 
        puts "consumed #{value}"
    end
end
  
#Waiting for the output of the consumer thread to complete before closing the process