Thread creation and management in Operating Systems - Time & Space Complexity
When we create and manage threads in an operating system, it is important to understand how the time taken grows as we increase the number of threads.
We want to know how the cost of starting and handling threads changes when we add more threads.
Analyze the time complexity of the following thread creation and management code snippet.
for (int i = 0; i < n; i++) {
pthread_create(&thread[i], NULL, thread_function, NULL);
}
for (int i = 0; i < n; i++) {
pthread_join(thread[i], NULL);
}
This code creates n threads and then waits for each to finish.
- Primary operation: Creating and joining each thread in a loop.
- How many times: Each loop runs exactly
ntimes, once per thread.
As the number of threads n increases, the total time to create and join all threads grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (10 creates + 10 joins) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The total operations increase linearly as the number of threads increases.
Time Complexity: O(n)
This means the time to create and manage threads grows directly in proportion to the number of threads.
[X] Wrong: "Creating multiple threads happens instantly and does not add up with more threads."
[OK] Correct: Each thread creation and join takes some time, so more threads mean more total time spent.
Understanding how thread creation time grows helps you design programs that use threads efficiently and avoid unexpected delays.
"What if threads were created recursively instead of in a loop? How would the time complexity change?"