0

I am not sure if I am doing this right, but here is my scenario: I need to create a thread to do some API call and continue with normal operations while the API call is made. This part is fine. The issue arises when I want to join back in. I am currently creating a thread in a different module and want to join back in a different module. Hence I am not able to use the reference to the thread created earlier.

To overcome this I did this: Thread.current[:ref_to_new_thread] = Thread.new { API CALL }

Finally I join back in a different module using - Thread.current[:ref_to_new_thread].join

Is this the right way? or is there a better way.

Minimal reproducible example:

File 1:

module A
 module Aa
  def my_method
   #some actions
   Thread.current[:ref_to_new_thread] = Thread.new { API CALL }
   #some actions
  end
 end
end

File 2:

module B
 module Bb
  def my_second_method
   #some actions
   Thread.current[:ref_to_new_thread].join
   Thread.current[:ref_to_new_thread] = nil
  end
 end
end

I am new to ruby on rails so my apologies.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • Some code would help. Sounds like you're not properly encapsulating things, hard to tell without a [mre]. – anothermh Feb 27 '20 at 21:04
  • There are so many options. You could pass the reference around. You could create a centralized service holding references to your thread(s). You could execute both, the "API calls" and the "normal operation" in threads and have the main thread control / coordinate both of them. You could use a [messaging system](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) and make the API thread send a message when it's ready / done. It's hard to tell what's the right / best approach here without any further details. – Stefan Feb 28 '20 at 07:51
  • @anothermh I tried my best to provide an example of what I am doing. – Jaleel Ahmed Feb 28 '20 at 16:56
  • @Stefan how would I do this - "You could execute both, the "API calls" and the "normal operation" in threads and have the main thread control / coordinate both of them." any documentation you could point me towards? Thanks. – Jaleel Ahmed Feb 28 '20 at 16:57
  • Better is relative, however I do want to point out that calling `my_method` twice without calling `my_second_method` will override `Thread.current[:ref_to_new_thread]`, thus loosing the handle to the the first created thread. – 3limin4t0r Feb 28 '20 at 17:47
  • ahh, I think I forgot to mention. The flow would shift towards my_second_method as soon as my_method is completed. But I get your point as well. @3limin4t0r – Jaleel Ahmed Feb 28 '20 at 20:45

0 Answers0