异步处理

异步处理 #

Thread #

创建线程 #

t = Thread.new {
  puts 'begin'
  puts 'end'
}
t.join
puts 'sync'
puts Thread.current

线程休眠 #

单位为秒

sleep(2)

线程中的异常 #

Ruby 中线程中的异常只会导致线程本身终止运行。但是如果使用了 join() 的话,则 join 的线程也会被停止。 此外,线程的 abort_on_exception 属性可以限制当发生异常时,所有线程都停止运行。

begin
  t1 = Thread.new {
    1 / 0
  }
  puts 'one'

  t2 = Thread.new {
    1 / 0
  }
  t2.abort_on_exception = true
  puts 'two'

  sleep(1)
rescue ZeroDivisionError
  puts 'error occurs'
end

ThreadLocal #

ThreadLocal 可以用于从线程中获取计算结果。

t = Thread.new {
  Thread.current['count'] = 10
}
t.join
print t['count']

同步锁 #

require 'thread'

mutex = Mutex.new

count1 = count2 = 0
difference = 0
Thread.new do
  loop do
    mutex.synchronize do
      count1 += 1
      sleep 0.1
      count2 += 1
    end
  end
end
Thread.new do
  loop do
    mutex.synchronize do
      difference += (count1 - count2).abs
    end
  end
end

sleep 1
mutex.lock
puts "count1 :  #{count1}"
puts "count2 :  #{count2}"
puts "difference : #{difference}"

协程 #

创建协程 #

require 'fiber'

f = Fiber.new do
  puts 'execute fiber()'
  Fiber.yield 1
  Fiber.yield 2
end

puts f.resume
puts f.resume

协程间协作 #

f1 = Fiber.new do |other|
  print 'hello'
  other.transfer
end

f2 = Fiber.new do
  puts ' world'
end

f1.resume f2
沪ICP备17055033号-2