Monday, March 10, 2014

Why we need Threads

As the time progress, man is becoming more and more impatient. In today's world of instant food, we want instant results. Gone are the time of batch processing and waiting days for a result. We like the program to finish execution asap. 

This is the major reason why we need threads. Threads aid in executing the program faster than before.

In real life also we do multiple things at the same time. A background process of breathing/heartbeat goes on while we perform daily chores. In office we type and talk at the same time. Similarly we like our program to do multi-tasking. This is achieve via Threads.



Before are few scenarios when usefulness of Threads become evident.

Case 1: Website and User Experience (Background Processing)
Consider a website running on a single thread. It takes an input from the user. While it is processing that input, what happens to the website? Use sees a hanged website. So much for user experience.

Solution: When website takes and input, a separate thread can work in background and do the processing, while user experience remains unhindered, enriching the overall quality.

Case 2: Query to a Database (Asynchronous Processing)
Consider a database call from a program. While database is taking its time to respond, the program is sitting is doing no processing. This slows down the overall execution.

Solution: Database query can be done by a separate thread, which waits for the result to be back. Overall it looks asynchronous. Program keeps on doing it's independent processing whilst, a separate thread id waiting for the Database results to be back.

Case 3: Multiple Processors
With the advent of multiple processors, single threaded programs are anyways at a loss. Parallel executions can occur in separate processors. To utilize that, multi-threaded code is a must.

Case 4: Simple Code
Just like recursion, which is difficult to understand but code becomes extremely simple. Same is the case with multiple threads. Code becomes extremely simple to write and modular. If we can divide our execution in separate paths, we should go for threads.

Programming example of multi-threading making things easier is Multithreaded QuickSort.