Example of producer consumer problem implemented by ruby thread (thread synchronization implemented by queue)


Ruby thread implements the classic producer consumer problem, and uses the queue class in ruby to implement the thread synchronization problem.

Copy codeThe code is as follows:
require “thread” 
puts “ProAndCon” 

Queue = queue.new – use queue to synchronize threads

producer = Thread.new do 
    10.times do |i| 
Sleep range (I) allows a thread to sleep for a period of time
        queue << i 
        puts “#{i} produced” 

consumer = Thread.new do 
    10.times do |i| 
        value = queue.pop 
        sleep rand(i/2) 
        puts “consumed #{value}” 

Consumer.join 訙 wait for the output of the consumer thread to complete before shutting down the process

Recommended Today

Python basics Chinese series tutorial · translation completed

Original: Python basics Python tutorial Protocol: CC by-nc-sa 4.0 Welcome anyone to participate and improve: a person can go very fast, but a group of people can go further. Online reading Apache CN learning resources catalog introduce Seven reasons to learn Python Why Python is great Learn Python introduction Executing Python scripts variable character string […]