Brain Dump

Thread

Tags
comp-arch

Short for thread-of-execution, meaning a series of instructions that the CPU has to execute.

Curiously a thread is a process. The core exception being the there's no copying of an existing processes address space when creating a new thread (as you would with fork). Instead multiple threads share the same address space, variables, heap, file descriptors, etc. as their parent process allowing you to access and modify them. Note: Each program gets its first thread free, and can use the pthread_create system call to create more threads.

If a program has more active threads than CPUs, the kernel will assign the thread to a CPU for a short duration or until it runs out of things to do and then will automatically switch the CPU to work on another thread. For example, one CPU might be processing the game AI while another thread is computing the graphics output.

Multiple Stacks

A thread by definition requires a stack, meaning in a multi-threaded program each thread is given its own stack despite them all sharing the same address space.

Multi-threaded Forking

A program can fork inside a process with multiple threads! However, the child process only has a single thread, which is a clone of the thread that called fork.

Advantages Over Processes

Creating a separate thread is more useful when:

  • You want to leverage the power of a multi-core system to do one task. Each thread can run on a separate core of the CPU.
  • When you can't deal with the overhead of processes.
  • When you want to communication between processes to be simplified.
  • When you want threads to be part of the same process.