What Is a Thread? The Unit of Execution
A thread is the smallest unit of execution a scheduler manages: a sequence of instructions that runs within a process and shares that process memory.
A program runs as a process, and inside that process one or more threads carry out the work. Each thread has its own call stack and runs its own sequence of instructions, but all threads in a process share the same heap and global memory. That shared memory makes threads cheap to coordinate, and also the source of concurrency bugs.
What a thread is
A thread is an independent path of execution with its own stack and program counter, living inside a process. The operating system schedules threads onto CPU cores, switching between them so multiple threads make progress.
Threads vs processes
A process is an isolated program with its own memory; a thread runs inside a process and shares that memory with sibling threads. Threads are lighter to create and communicate faster, but a bug in one thread can corrupt shared state for all of them.
What threads share and do not
- Shared: heap memory, global variables, open files, the address space.
- Private: each thread own call stack and registers.
- Shared state is what enables fast communication between threads.
- Shared state is also what makes races and deadlocks possible.
The cost of threads
Threads are cheaper than processes but not free: each has a stack, and the OS spends time switching between them. Spawning thousands of threads can exhaust memory or thrash the scheduler, which is why many systems use thread pools.
A quick example
A test runner might use a pool of worker threads to execute many test files at once, with each worker thread pulling the next file from a shared queue.
Threads in CI
Thread-heavy test runs can saturate the cores and memory of a small runner, slowing down or hitting OOM. Bigger runners (Latchkey) give threads real cores to run on, and transient OOM kills from thread or memory spikes can be auto-retried.
Key takeaways
- A thread is the smallest schedulable unit of execution, running inside a process.
- Threads share heap and globals but each has its own stack.
- Shared memory makes threads fast to coordinate but enables races and deadlocks.