面试题答案
一键面试require 'thread'
# 共享资源
shared_variable = 0
mutex = Mutex.new
# 创建多个线程
threads = []
5.times do
threads << Thread.new do
mutex.lock
begin
shared_variable += 1
puts "Thread #{Thread.current.object_id} incremented shared_variable to #{shared_variable}"
ensure
mutex.unlock
end
end
end
# 等待所有线程完成
threads.each(&:join)