Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Rails multi-threaded in development?

I am working on a multiple projects that talk to each other sometimes and I've run into an issue where app

  1. A calls B (request 1, still running)
  2. B calls A (request 2)
  3. based on request 2's result, B responds to request 1

This requires me running multi-threaded rails in development mode.

I know I can set it up using puma or something like that but ... Isn't there really a simpler way?

I would like to avoid changing anything in the project (adding gems, config files..).

Something like rails s --multi would be nice, can't webrick just run with multiple threads or spawn more processes?

Can I perhaps install a standalone gem to do what I need and run something like thin run . -p 3?

like image 853
hakunin Avatar asked Jul 25 '17 18:07

hakunin


People also ask

How do you use multithreading in Ruby?

In Ruby, a multi-threaded program is created with the help of Thread class and a new thread is created by calling a block, i.e Thread. new. In Ruby, creating a new thread is very easy. There are three blocks (Thread.

Is Ruby on Rails multi-threaded?

Dissecting Ruby on Rails 5 - Become a Professional Developer Often on a single CPU machine, multiple threads are not actually executed in parallel, but parallelism is simulated by interleaving the execution of the threads. Ruby makes it easy to write multi-threaded programs with the Thread class.

What is multi-threaded development?

Multithreading is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.

How is Multi threading achieved?

By extending the Thread class: When a child class is created by extending the Thread class, the child class represents that a new thread is executing some task. When extending the Thread class, the child class can override only two methods i.e. the __init__() method and the run() method.


1 Answers

The puma web server can provide multi-threading and multiple workers bound to a single local address.

  1. Install the puma gem:

    bundle add puma
    

    or

    gem install puma
    
  2. Add a puma configuration file at config/puma.rb:

    workers 1 # 1 worker in addition to master instance (i.e. handle 2 requests concurrently).
    preload_app!
    
  3. Launch the Rails server.

    bundle exec rails s
    

    Puma automatically starts and loads in the config file at config/puma.rb.

Bump up the value for workers if you need to handle more than 2 concurrent requests at the same time.

like image 154
Denis Avatar answered Oct 13 '22 11:10

Denis