Ruby并发编程 #

一、Thread #

1.1 创建线程 #

ruby
thread = Thread.new do
  puts "Thread running"
end

thread.join

1.2 线程操作 #

ruby
thread = Thread.new { sleep 1; "result" }
thread.status
thread.alive?
thread.value
thread.join

1.3 多线程 #

ruby
threads = 5.times.map do |i|
  Thread.new { puts "Thread #{i}" }
end

threads.each(&:join)

二、Mutex #

ruby
mutex = Mutex.new
counter = 0

threads = 10.times.map do
  Thread.new do
    mutex.synchronize do
      counter += 1
    end
  end
end

threads.each(&:join)
puts counter

三、Fiber #

ruby
fiber = Fiber.new do
  puts "Fiber started"
  Fiber.yield "paused"
  puts "Fiber resumed"
  "finished"
end

puts fiber.resume
puts fiber.resume

四、总结 #

本章我们学习了:

  1. Thread:创建、操作、多线程
  2. Mutex:线程同步
  3. Fiber:协程

接下来让我们学习Ruby的Gem包管理!

最后更新:2026-03-27