Ruby 多线程

简单情况

# gem install e2mmap thwait
require 'thwait'
a = Thread.new { sleep 1 }
b = Thread.new { sleep 2 }
ThreadsWait.all_waits(a, b) { |t| p t }

大量任务

# 获取内核线程数
require 'etc'
Etc.nprocessors

require 'thread'
num_workers = 20 # Etc.nprocessors
queue = Queue.new
end_object = Object.new # SizedQueue.new(num_workers * 2)
threads = num_workers.times.map do
  Thread.new do
    until (item = queue.pop) == end_object
      do_something(item)
    end
  end
end
list.each { |item| queue << item }
num_workers.times { queue << end_object }
threads.each(&:join)

Promise, Async/Await

Concurrent Ruby,太杂了 (x

Common Practice

EventMachinenio4r

参考