Threading deep dive – Day 1

Recently I gave a session to our team members about threads and Thread pools in .NET. I made deep dive into every aspect of threading starting from what is thread, clock pulse, CPU instruction cycle and etc. I wanted to share the same to my blog.

Thread is a unit of execution within any process. Since it is the unit of execution any process will have a minimum of one thread. Without thread(s) application cannot execute. Thread is what makes the application run. If all of your application threads die then your application terminates. We will see the different kinds of thread available and differences between them later. Below are important things to know before we proceed into the deep dive.

What is Clock pulse? It is kind of heart beat for the processor that it receives from the clock pulse generator. The speed at which a computer can generate pulse would determine the speed of that computer. Say for example, if your computer speed is 2GHZ, it means that your computer generates 2 X 10^9 pulses per second. Each and every pulse makes the processor to execute one low level operation. The processor has to perform many such low level operations to complete a simple instruction from your program. According to the type of the instruction from your program, the number of low level operations the processor has to perform will vary.

What is CPU cycle / Processor cycle? It is sequence of clock pulses required to execute one instruction from your program. Below is list of low level operations the computer has to perform [roughly] to execute any instruction from your program.

  1. Check the program counter to find the address of the next instruction
  2. Load the next instruction from memory into the instruction register
  3. Update the program counter to point at the next instruction
  4. Resolve the type of instruction brought
  5. If the instruction requires data from memory, resolve the address of the same
  6. Load the data from memory into CPU register
  7. Execute the instruction
  8. Return to point number 1 for the next instruction

On every clock pulse the processor performs the above listed low level operations one after another in a sequence. So approximately, to execute a simple instruction from your program, the processor needs at least 8 clock pulses. If you want to write a good performing code, think on each and every line of code as to not to waste processor cycles.