Ruby中用线程实现经典的生产者消费者问题代码实例
程序员文章站
2022-05-14 18:34:13
示例代码:
复制代码 代码如下:
require "thread"
puts "proandcon"
queue = queue....
示例代码:
复制代码 代码如下:
require "thread"
puts "proandcon"
queue = queue.new #用队列queue实现线程同步
producer = thread.new do
10.times do |i|
sleep rand(i) # 让线程睡眠一段时间
queue << i
puts "#{i} produced"
end
end
consumer = thread.new do
10.times do |i|
value = queue.pop
sleep rand(i/2)
puts "consumed #{value}"
end
end
consumer.join #等待consumer线程的输出完成再关闭此进程
运行结果:
复制代码 代码如下:
proandcon
produced
produced
consumed 0
produced
produced
consumed 1
consumed 2
consumed 3
produced
consumed 4
produced
consumed 5
美化的代码图:
上一篇: 磁贴拜拜!老外打造心目中完美Windows 10开始菜单
下一篇: 复习Python中的字符串知识点