欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ruby实现生产者和消费者代码分享

程序员文章站 2022-04-28 22:21:57
#ruby实现生产者和消费者代码 require 'thread' queue = queue.new consumers = thread.new d...
#ruby实现生产者和消费者代码
 
require 'thread'
queue = queue.new
consumers = thread.new do
  5.times do |i|
    obj = queue.pop
    print "consumer :#{i}\n"
    sleep(rand(0.05))
  end
end
 
producters = thread.new do
  5.times do |i|
    sleep(0.1)
    print "producter : #{i}\n"
    queue.push("item #{i}")
  end
end
 
producters.join
consumers.join