I am working on a multiple projects that talk to each other sometimes and I've run into an issue where app
request 1
, still running)request 2
)request 2
's result, B responds to request 1This 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
?
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.
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.
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.
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.
The puma web server can provide multi-threading and multiple workers bound to a single local address.
Install the puma gem:
bundle add puma
or
gem install puma
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With