MST

星途 面试题库

面试题:Ruby中线程安全与同步机制之基础运用

在Ruby中,假设你有一个共享资源(比如一个全局变量),需要在多线程环境下访问,你如何使用Mutex来确保线程安全?请编写一段简单代码示例。
47.3万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
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)