目前我有一些类似的代码
class WorkingWithThread
def self.start_first_thread
@@first_thread = Thread.new do
do something
repeat # infinitive loop
end
end
def self.start_second_thread
@@second_thread = Thread.new do
do something
repeat # infinitive loop
end
end
def self.stop_thread
begin
Thread.kill @@first_thread
Thread.kill @@second_thread
p 'STOP THREAD'
rescue Exception => e
p 'NO THREAD OPENING'
end
end
end
最大线程池为3,超时= 600秒。我发出了2个api请求来启动和停止线程。
有效。但是,如果启动api被调用两次,则变量@@ first_thread和@@ second_thread似乎已重新初始化,并且那些正在运行的线程无法终止。此外,有时过一会儿,即使我只调用一次启动api,停止api也不起作用(需要说明)。
问题是:
如何存储线程变量,这样就可以在不使用数据库的情况下将其停止?
我正在考虑在线程正在运行时添加方法来阻止启动api?可行吗?如果是的话,作为我上面提到的无法解释的原因,如何停止这些线程?
class WorkingWithThread
attr_accessor :first_thread, :second_thread
def run
start_first_thread
start_second_thread
end
def start_first_thread
return puts("First thread already running") if self.first_thread
puts "Launching thread one!"
self.first_thread = Thread.new do
# do something
repeat # infinite loop
end
end
def start_second_thread
return puts("Second thread already running") if self.second_thread
puts "Launching thread two!"
self.second_thread = Thread.new do
# do something
repeat # infinite loop
end
end
def stop_threads
begin
Thread.kill first_thread if first_thread
Thread.kill second_thread if second_thread
p 'STOP THREADS'
rescue Exception => e
p 'NO THREADS OPENING'
end
end
end
然后使用它:
worker = WorkingWithThread.new
worker.run
# => Launching thread one!
# => Launching thread two!
worker.run
# => First thread already running
# => Second thread already running
worker.stop_threads
# => STOP THREADS
这样,您将可以始终访问正在运行的线程-让我知道是否有帮助以及您如何继续::]