Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save variable without using database in ruby

Currently I have some code like this:

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

Max threads pool is 3, timeout = 600 secs. I made 2 api requests to start and stop threads.

It works properly. However, if the start api is called 2 times, the variables @@first_thread and @@second_thread seems to be reinitialized and those running threads can't be killed. In addition, after a while, sometimes, the stop api also doesn't works even when I call start api one time only (i need explanation here).

The questions is:

  1. How to store thread variables so I can stop it without using database?

  2. I'm thinking about adding method to block start api when there are running threads? Is it viable? If it is, how to stop those threads when it happens as unexplained reason that i mentioned above?

like image 410
Hùng Nguyễn Avatar asked Mar 09 '26 09:03

Hùng Nguyễn


1 Answers

Why not instantiate an instance of the class and store the running threads there? For example:

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

Then to use it:

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

That way you'll have access to the running threads throughout - let me know if that helps and how you get on :)

like image 71
SRack Avatar answered Mar 11 '26 01:03

SRack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!