What are Threads?
When you run a computer program, it starts a process. That process can spawn additional processes. In turn, each of those processes can spawn threads. What's the difference between threads and processes, and how do they get run by the computer?
I was confused by this for a long time, but it clicked for me when someone explained that:
- CPU cores execute threads, not processes
- The operating system is responsible for scheduling threads onto cores
- All threads in a process share the same memory address space, code segments, and file descriptors
- Each thread has its own program counter, which points to the next instruction to be executed
- Processes must have at least one thread to be considered alive
An interactive food analogy may clarify things:
In a food court computer, there can be several restaurants processes each with several orders threads. Each chef CPU core works on one order thread at a time. A chef CPU core could be assigned to a different order thread (even one belonging to another restaurant process) at any time. Before switching, they will record which instruction of the recipe code segment was last completed so that the next chef CPU core that comes along can resume the order thread. Chefs CPU cores that are working on orders threads in the same restaurant process will share the same kitchen memory address space, and thus need to coordinate.
As a side note, some programming languages have functionality to emulate OS-threads. These are known as green threads. The language runtime, not the operating system, is responsible for scheduling and context switching between green threads.