gpt4 book ai didi

ruby-on-rails - 如何在不使用ruby数据库的情况下保存变量

转载 作者:行者123 更新时间:2023-12-02 02:42:32 29 4
gpt4 key购买 nike

目前我有一些这样的代码:

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 被调用 2 次,变量 @@first_thread@@second_thread 似乎被重新初始化并且那些正在运行的线程无法被杀死。此外,一段时间后,有时,即使我只调用一次启动 api,停止 api 也不起作用(我需要在这里解释一下)。

问题是:

  1. 如何存储线程变量以便在不使用数据库的情况下停止它?

  2. 我正在考虑添加方法以在有线程运行时阻止启动 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

这样您就可以始终访问正在运行的线程 - 让我知道这是否有帮助以及您的进展情况:)

关于ruby-on-rails - 如何在不使用ruby数据库的情况下保存变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58424454/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com