Tuesday, October 21, 2014

What is a Thread?

Thread relates to running of a program. A Thread is a single chain of execution within a program.

This above start to end path within a program is called a Thread. These steps can do a number of operations. For example if we are adding two numbers input by the user. This thread execution will comprise of the below steps:

1. Asking user for the input 1
2. Asking user for the input 2
3. Adding the two inputs
4. Printing the final sum.

A single program can have multiple executions in parallel. As in multiple threads. For example finding the sum of 10 input numbers.

Two separate threads can take 5 inputs separately and add them up. At the end, the two results can be added together to get the final sum. It's not that work speed increases magically. It's just a illusion, a trick by a magician.

Salient Features of a Thread
1. Thread is like a sub-process. Multiple thread paths can exist within a single process.
2. All threads share the same resources (memory, variables) within a process. This can result into conflict, hence needs to be handles carefully.
3. Apart from shared resources, each thread has its own stack space where it stores variables local to it.
4. One can argue that we can create multiple processes, then why is the need for multiple threads. You can read about it here. Multiple threads v/s Multiple processes.

No comments:

Post a Comment