0
0
Rubyprogramming~5 mins

Thread creation and execution in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Thread creation and execution
O(1)
Understanding Time Complexity

When we create and run threads, we want to know how the time to finish changes as we add more threads.

We ask: How does running many threads affect the total time the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

threads = []
10.times do |i|
  threads << Thread.new do
    sleep(1)  # Simulate work
    puts "Thread #{i} done"
  end
end
threads.each(&:join)

This code creates 10 threads that each wait for 1 second, then print a message. The main program waits for all threads to finish.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Creating and running 10 threads that each sleep for 1 second.
  • How many times: The thread creation loop runs 10 times, and each thread runs its code once.
How Execution Grows With Input

Imagine increasing the number of threads (n) that each sleep for 1 second.

Input Size (n)Approx. Operations (seconds)
10About 1 second total
100About 1 second total
1000About 1 second total

Pattern observation: Because threads run at the same time, total time stays about the same even as we add more threads.

Final Time Complexity

Time Complexity: O(1)

This means the total time to run all threads stays roughly the same no matter how many threads we create, assuming they run in parallel and the system can handle them concurrently.

Common Mistake

[X] Wrong: "More threads always mean the program takes longer to finish."

[OK] Correct: Threads run at the same time, so adding more threads does not always increase total time if the system can handle them concurrently.

Interview Connect

Understanding how threads affect time helps you explain how programs can do many things at once, a useful skill in real projects and interviews.

Self-Check

"What if each thread did a task that took longer than 1 second? How would the total time change then?"