Threading Simplified: Part 1 (Threads Inception)

Threading in .Net is an important topic. I have seen people unable to understand the nuances of processes, threads and how they are related in .Net and also in general.

In the series of articles around threading, I will try to present the concepts in the simplest way possible so that it can knock to your head directly and help you understand easily.

Threading is a broad topic that goes with operating systems. So before beginning the threading in .Net let's understand a few core or underlying concepts as in the following.

How applications and processes are related

When we start an application, system resources and memory are assigned to it. The separation of these boundaries are based on memory and the resources are called a process.

An application can be allocated one or more processes, where each process is differentiated based on allocated resources, data and execution code.


Processes

A process can be defined as an instance of the application. While running it uses assigned program code, system resources and data. A process further can be broken into more than one thread based on application design and the operating system of the machine.

Threads

A thread can be defined as the smallest possible part of the process that can be handled or controlled independently by a scheduler. If I make an analogy to it then you can relate it to atom in the world of matters/particles.

How processes and threads are related

Every thread is a part of a process. Multiple threads within a process share the memory, execution instruction, context data and other system resources.

The following picture explains the relationship among applications, processes and threads.


How threading works internally

As said above, each process has its own execution instruction/sequence, context, memory and other system resources. The part or constituents that makes threads to work can be defined as in the following.

  • Registers (in the CPU) 
  • Memory Stack
  • Container to store threads state/context (in other words TLS)

TLS

I assume you understand what context switching is in threading. In simple words, it's switching the focus to various threads involved in the system based on certain algorithms (you might have heard of Round Robin and so on). In this scenario, the outgoing thread needs to store its state information to be able to start form the same place (again when it gets the slot). Basically this is done by TLS that uses a program counter that tells the thread which instruction to execute next.

Multithreading

Well, that's enough for the first tutorial. :) I will explain multithreading in the next article.

Please share your comments.

Up Next
    Ebook Download
    View all
    Learn
    View all