Ruby Thread 類別提供輕量級平行處理能力。本文涵蓋執行緒建立、生命週期、例外傳播、執行緒區域變數、優先順序調整、Mutex 互斥鎖同步化共享資源,並提供完整範例程式碼。
t = Thread.new { puts "Thread #{Thread.current.object_id} running" }
t.join # 等待結束
Thread.new 建立並自動啟動。Thread.current 取得目前執行緒物件。Thread.main 主執行緒。t.value 取得區塊最後運算式值(會阻塞至執行緒結束)。t.join 等待執行緒結束。def func1; 3.times { |i| puts "func1 at #{Time.now}"; sleep 2 } end
def func2; 3.times { |j| puts "func2 at #{Time.now}"; sleep 1 } end
puts "Started at #{Time.now}"
t1 = Thread.new { func1 }
t2 = Thread.new { func2 }
t1.join; t2.join
puts "End at #{Time.now}"
Thread.abort_on_exception = true,任何未捕捉例外導致整個程式退出。t.join 或 t.value 時,子執行緒的例外會在呼叫端重新拋出。count = 0
threads = 10.times.map do |i|
Thread.new {
sleep(rand/10.0)
Thread.current["mycount"] = count
count += 1
}
end
threads.each { |t| t.join; print t["mycount"], ", " }
puts "count = #{count}"
Thread#priority 讀取/設定優先順序(數值越高優先)。require 'thread'
mutex = Mutex.new
counter = 0
threads = 10.times.map {
Thread.new { 1000.times { mutex.synchronize { counter += 1 } } }
}
threads.each(&:join)
puts counter # 10000
無鎖風險: 移除 mutex.synchronize 會導致 counter 因競態條件而小於 10000。