MST

星途 面试题库

面试题:Ruby 并发编程中的线程同步机制

在 Ruby 中,假设有多个线程需要访问并修改同一个共享资源,你会使用哪些线程同步工具(如 Mutex、Condition Variable 等)来确保数据的一致性,并举例说明如何实现?
14.9万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
  1. Mutex(互斥锁)
    • 作用:Mutex 用于保证在同一时间只有一个线程能够访问共享资源,从而避免数据竞争。
    • 示例代码
require 'thread'

shared_resource = 0
mutex = Mutex.new

threads = []
5.times do
  threads << Thread.new do
    mutex.lock
    shared_resource += 1
    puts "Thread #{Thread.current.object_id} incremented shared_resource to #{shared_resource}"
    mutex.unlock
  end
end

threads.each(&:join)
  1. Condition Variable(条件变量)
    • 作用:Condition Variable 通常与 Mutex 一起使用,用于线程间的同步。它允许线程在满足某些条件时被唤醒,避免不必要的忙等待。
    • 示例代码
require 'thread'

shared_resource = 0
mutex = Mutex.new
condition = ConditionVariable.new

producer = Thread.new do
  loop do
    mutex.lock
    shared_resource += 1
    puts "Producer incremented shared_resource to #{shared_resource}"
    condition.signal
    mutex.unlock
    sleep 1
  end
end

consumer = Thread.new do
  loop do
    mutex.lock
    condition.wait(mutex) unless shared_resource > 0
    value = shared_resource
    shared_resource = 0
    puts "Consumer consumed value #{value}"
    mutex.unlock
  end
end

producer.join
consumer.join