如何在ruby中重新处理抛出异常的线程中的项?
我使用线程和队列处理项目,但有时会为特定项目引发异常,因此无法对其进行处理 我的想法是将有问题的项目放回队列中,以便可以再次处理它,并一直放回队列,直到不再抛出异常为止 尽管我打算重新处理项目,但此代码只处理队列一次:如何在ruby中重新处理抛出异常的线程中的项?,ruby,multithreading,exception-handling,Ruby,Multithreading,Exception Handling,我使用线程和队列处理项目,但有时会为特定项目引发异常,因此无法对其进行处理 我的想法是将有问题的项目放回队列中,以便可以再次处理它,并一直放回队列,直到不再抛出异常为止 尽管我打算重新处理项目,但此代码只处理队列一次: #assume this queue is immediately filled with items item_queue = Queue.new define_method (:processItem) {|item| begin #do something
#assume this queue is immediately filled with items
item_queue = Queue.new
define_method (:processItem) {|item|
begin
#do something with item
#Bad style below: will work in specific exception handling later
rescue Exception => ex
#something happened, so put it back in the queue
item_queue << item
return
end
#more processing here, if 'begin' was successful
}
threads = []
until item_queue.empty?
threads << Thread.new{ processItem(item_queue.pop) }
end
threads.each{|thread| thread.join}
#假设此队列中立即充满了项目
item_queue=queue.new
定义_方法(:processItem){|项|
开始
#对这个项目做些什么
#下面的错误样式:将在以后的特定异常处理中使用
营救异常=>ex
#发生了什么事,所以把它放回队列
item_queueYesqueue
是线程安全的,但您使用它的方式并不安全
item\u queue.empty?
可能在线程完成之前返回true
调用Thread.join
在内部加入,直到项目_队列。empty?
将解决竞争条件问题,但最终将得到一个程序,该程序一次处理队列中的一个项目
until item_queue.empty?
Thread.new{ processItem(item_queue.pop) }.join
end
如果希望以多线程方式处理队列中的项目,则需要预定义需要多少线程,例如:
# three threads processing items in the queue
until item_queue.empty?
t1 = Thread.new{ processItem(item_queue.pop) }
t2 = Thread.new{ processItem(item_queue.pop) }
t3 = Thread.new{ processItem(item_queue.pop) }
t1.join 1
t2.join 1
t3.join 1
end
是的Queue
是线程安全的,但您使用它的方式并不安全
item\u queue.empty?
可能在线程完成之前返回true
调用Thread.join
在内部加入,直到项目_队列。empty?
将解决竞争条件问题,但最终将得到一个程序,该程序一次处理队列中的一个项目
until item_queue.empty?
Thread.new{ processItem(item_queue.pop) }.join
end
如果希望以多线程方式处理队列中的项目,则需要预定义需要多少线程,例如:
# three threads processing items in the queue
until item_queue.empty?
t1 = Thread.new{ processItem(item_queue.pop) }
t2 = Thread.new{ processItem(item_queue.pop) }
t3 = Thread.new{ processItem(item_queue.pop) }
t1.join 1
t2.join 1
t3.join 1
end
我读过,特别是关于异常处理的部分。我读过,特别是关于异常处理的部分。