user7055375
user7055375

Reputation:

How can I manage multiple threads in Ruby on Rails (equivalent of a Java thread factory)?

I'm using Ruby on Rails 5 although I'm fairly a novice to Ruby/Rails. I have read about creating threads using

   t = Thread.new {
      sleep(rand(0)/10.0)
      Thread.current["mycount"] = count
      count += 1
   }

However, I'm wondering if there is a standard way of managing a bunch of application-created threads in Ruby/Rails. I'm familiar with Java, which has a thread factory. That allows a certain number of threads to concurrently run while others must wait in a queue. I'm wondering how I would do something similar in Ruby/Rails.

Note that I'm not talking about the types of threads that are generated automatically when a web page is requested. I'm talking about threads that I (the application owner) creates.

Upvotes: 2

Views: 5623

Answers (2)

Ismael
Ismael

Reputation: 16730

I think https://github.com/ruby-concurrency/concurrent-ruby is the most used library with utils for concurrency in ruby.

It has a lot of useful things including Thread Pools (http://ruby-concurrency.github.io/concurrent-ruby/file.thread_pools.html) which I think is what you are looking for.

Keep in mind that MRI Ruby has GIL, so you only have parallelism if your threads are waiting for IO. For heavy computation you might want to use jRuby or look elsewhere :)

Upvotes: 1

Coolness
Coolness

Reputation: 1992

Especially if you're using ActiveRecord inside your threads, you need to be careful about concurrency issues with for example database connections leaking.

Usually if you want to launch a new thread, you want to do something asynchronously in the background without having the user's request hang on an expensive action. For this there are some great libraries like Sucker Punch and Sidekiq. I'd recommend using one of these instead of creating and managing threads manually.

Hope this helps

Upvotes: 1

Related Questions