0
0
Rubyprogramming~3 mins

Why Thread creation and execution in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could do many things at once, just like having many hands helping you?

The Scenario

Imagine you have to bake 10 cakes, but you only have one oven and one tray. You bake one cake at a time, waiting for each to finish before starting the next.

The Problem

This slow, one-by-one baking means you waste a lot of time waiting. If you try to do many tasks in a row without help, your program also waits and wastes time doing nothing.

The Solution

Thread creation lets your program start many tasks at once, like having multiple ovens baking cakes simultaneously. This way, your program works faster and uses time better.

Before vs After
Before
10.times { |i| puts "Baking cake #{i+1}"; sleep(2) }
After
threads = 10.times.map { |i| Thread.new { puts "Baking cake #{i+1}"; sleep(2) } }; threads.each(&:join)
What It Enables

Threads let your program do many things at the same time, making it faster and more efficient.

Real Life Example

When a website loads images, text, and videos all at once instead of waiting for each to finish, it feels faster and smoother to use.

Key Takeaways

Doing tasks one after another wastes time.

Threads let multiple tasks run together.

This makes programs faster and more responsive.