【发布时间】:2016-03-01 16:10:12
【问题描述】:
我需要让一个线程自行停止,然后被另一个线程唤醒。我的问题是我找不到一个完全万无一失的好解决方案。我现在的代码如下所示:
def initialize
@data_lock = Mutex.new
@closed = false
end
def get_response
@data_lock.synchronize do
@blocked_thread = Thread.current
end
# This loop is a safe guard against accidental wakeup of thread
loop do
@data_lock.synchronize do
if @closed
return @response
end
end
# FIXME: If context switch happens here the thread will be permanently frozen.
Thread.stop # Stop current thread and wait for call to close()
end
end
def close(response)
@data_lock.synchronize do
@closed = true
@response = response
Thread.pass # An attempt at minimizing the risk of permanently freezing threads
if @blocked_thread.is_a? Thread and @blocked_thread.status == 'sleep'
@blocked_thread.wakeup
end
end
end
它的工作方式是调用 get_response 将阻塞当前线程,当另一个线程调用 close() 时,第一个线程应该被唤醒并返回通过 @response 发送的值。
这应该适用于所有情况,除非在第一个线程停止之前第二个线程调用 close 并且在第一个线程停止之前有一个上下文切换。我怎样才能消除这种(非常不可能)的可能性?
【问题讨论】:
标签: ruby multithreading concurrency mutex