saba saba - 4 years ago 77
Ruby Question

How to Kill threads that are present in Controller in its model (Ruby 2.1.2 on Rails 3.2.13)

I have a controller RamsController in that I have this method

def check_status
@ram = Ram.find(params[:id])
if @ram.workflow == "start"
thread_status = Thread.new do
thread.current[:name] = "thread_check_status"
@ram.check_status!
ActiveRecord::Base.connection.close
end
@ram.thread_check_status = thread_status
end
render json: { status: "success" }
end


I have a model code like this

class Ram < ActiveRecord::Base

attr_accessor :thread_check_status

def self.kill_threads
self.thread_check_status.kill
end

def exception_handler(exception)
if exception == "exited by user"
self.kill_threads
end
end


Whenever an exception is caught it will go to the exception_handler method in the model.
And now, I'm trying to kill the thread when the exception is caught so I tried to assign the thread to the variable
@ram.thread_check_status = thread_status
So I created a method
def self.kill_threads
in the model to kill the threads and called that method in
def excpetion_handle
method.

But, it is not working I think I assigned the thread to the variable in a wrong way
@ram.thread_check_status = thread_status


Please suggest me how to kill the threads associated with
@ram
id in the model.

And I have two more methods in RamsController with two more threads and I'm trying kill those threads too.

Answer Source

I come up with a solution like this. Firstly, in the controller I set the thread variable with a name and value like this

def check_status
   @ram = Ram.find(params[:id])
   if @ram.workflow == "start"
      Thread.new do

Thread.current.thread_variable_set(:thread_name, @ram.id)#This will set the thread value to ram_id

         @ram.check_status!
         ActiveRecord::Base.connection.close
      end
      @ram.thread_check_status = thread_status
   end
  render json: { status: "success" }
end

So in the model I listed all the threads available and killed the thread which is associated with ram_id, thread_name

class Ram < ActiveRecord::Base

attr_accessor :thread_check_status 



  def exception_handler(exception)

Thread.list.each do |thr|

if thr.thread_variable_get(:thread_name) == self.id

thr.kill

end

end

   if exception == "exited by user"
     self.kill_threads
   end
end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download