0
0
Rubyprogramming~5 mins

Why concurrency matters in Ruby

Choose your learning style9 modes available
Introduction

Concurrency helps Ruby programs do many things at the same time. This makes programs faster and more efficient, especially when waiting for slow tasks like reading files or talking to the internet.

When your program needs to download many files from the internet at once.
When you want to handle multiple users talking to a chat app at the same time.
When your program needs to do long calculations but also respond quickly to user actions.
When you want to keep your app running smoothly while waiting for slow tasks like database queries.
Syntax
Ruby
# Ruby uses threads for concurrency
thread = Thread.new do
  # code to run in parallel
end
thread.join  # wait for thread to finish
Ruby uses threads to run code at the same time within the same program.
Threads share memory, so be careful to avoid conflicts when changing data.
Examples
This creates a new thread that prints a message. The main program waits for it to finish.
Ruby
thread = Thread.new do
  puts "Hello from thread"
end
thread.join
This starts 5 threads that run at the same time, each printing its number.
Ruby
threads = []
5.times do |i|
  threads << Thread.new do
    puts "Thread #{i} is running"
  end
end
threads.each(&:join)
Sample Program

This program shows how the main program and a thread run together. The thread waits 1 second before printing, while the main program continues immediately.

Ruby
puts "Main program starts"
thread = Thread.new do
  sleep 1
  puts "Hello from thread after 1 second"
end
puts "Main program continues"
thread.join
puts "Main program ends"
OutputSuccess
Important Notes

Ruby's Global Interpreter Lock (GIL) means only one thread runs Ruby code at a time, but threads still help with waiting tasks.

For true parallel execution of CPU-heavy tasks, Ruby can use multiple processes instead of threads.

Summary

Concurrency lets Ruby programs do many things at once, improving speed and responsiveness.

Threads are the main way to add concurrency in Ruby.

Use concurrency when your program waits for slow tasks or handles many users.