How is the Thread internally implemented?

There are many ways to implement threading, but most modern programming language implementations generally use the operating system kernel's threading capabilities. For the language developer, it's left up to a library call into the kernel.
Within the kernel, threading essentially comes down to an interrupt. The program is loaded into memory and the CPU's instruction pointer set to the current memory location, which causes the CPU to start executing that program. After a predetermined time, or number of instructions, or when the program has to wait for something to arrive from an I/O device, etc. the interrupt fires and control switches automatically back to the operating system.

The OS then decides where to go from here. It may pick another thread to give control to, if there's a queue waiting. When that happens, a "context switch" occurs: the registers in the CPU are saved off to some other part of memory, and the other thread's register set is switched in. Then the instruction pointer is switched to the other program's memory, and off it goes. The program switches back and forth to allow both programs access to the CPU and they seem to run in parallel,


There are about a billion complexities I'm glossing over here, like shared memory, virtual memory, hyperthreading, semaphores, multicore CPUs, etc. but that's the gist.

0 comments:

Post a Comment

My Instagram