- 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)
- 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