Ruby 中的多进程运行与单元测试
多进程运行
在编程过程中,有时我们需要将一个任务拆分成多个进程大小的块,或者运行一个非 Ruby 编写的独立进程。Ruby 提供了多种方法来生成和管理独立进程。
多线程示例
以下是一个简单的多线程示例,模拟客户请求和播放音乐的过程:
plays_pending = playlist.new_cond
# Customer request thread
customer = Thread.new do
loop do
req = get_customer_request
break unless req
playlist.synchronize do
playlist << req
plays_pending.signal
end
end
end
# Player thread
player = Thread.new do
loop do
song = nil
playlist.synchronize do
break if ok_to_shutdown && playlist.empty?
plays_pending.wait_while { playlist.empty? }
song = playlist.shift
end
break unless song
play(song)
end
end
customer.join
ok_to_shutdown = true
player.jo
超级会员免费看
订阅专栏 解锁全文

3819

被折叠的 条评论
为什么被折叠?



