The classic producer Consumer problem code instance _ruby with threads in Ruby topics

Source: Internet
Author: User
Tags rand

Sample code:

Copy Code code as follows:

require "thread"
puts "Proandcon"
  
Queue = Qu eue.new    #用队列Queue实现线程同步  
  
producer = thread.new do
  &NB Sp 10.times do |i| 
        sleeping rand (i) # Let threads sleep for a period of time  
&NBSP;&NBSP ;      queue << i 
        puts #{i} Produced '
    end
'
  
consumer = thread.new do
     10.times do |i| 
        value = queue.pop 
         Sleep rand (I/2)  
        puts "consumed {value} '
    end
'
  
consumer.join  #等待consumer线程的输出完成再关闭此进程

Run Result:

Copy Code code as follows:

Proandcon
Produced
Produced
Consumed 0
Produced
Produced
Consumed 1
Consumed 2
Consumed 3
Produced
Consumed 4
Produced
Consumed 5

Landscaping Code Map:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.