OS//thread

A thread is the unit of execution that the kernel schedules on a core: one sequence of instructions with its own program counter, registers and stack, living inside an OS process and sharing that process's memory, open files and permissions with every other thread of it. It is how one program uses several cores at once, or keeps one task blocked on a disk while another keeps working, without paying for a second process.


A thread is the unit of execution that the kernel schedules on a core: one sequence of instructions with its own program counter, registers and stack, living inside an OS process and sharing that process's memory, open files and permissions with every other thread of it. It is how one program uses several cores at once, or keeps one task blocked on a disk while another keeps working, without paying for a second process.

The process owns the resources and the thread runs on them. A server that handles each request on its own thread has one address space, one set of open sockets and one identity, and many threads moving through them at once; a server that forks a child process per request has as many separate memories as requests. Threads are therefore cheaper to start and to switch between, and they can hand data to each other by writing a variable, with no pipe or socket in between.

Threads share memory, so they share failure.

The sharing that makes them cheap means a thread that corrupts memory or crashes takes the whole process down with all its threads, and two threads that touch the same data without a mutex produce races whose outcome depends on timing (concurrency). Work that must be able to fail alone goes in its own process.

A thread is not free. Each one has its own stack, reserved by default at 8 MB of address space on most Linux systems (the ulimit -s setting; only the pages actually touched take real memory), and a slot in the kernel's scheduler. A task parked in asynchronous programming costs a few kilobytes, which is why a server holding ten thousand idle connections uses an event loop rather than ten thousand threads.

In CPython the GIL lets only one thread run Python bytecode at a time, so threads overlap waits (network, disk) but do not speed up pure arithmetic; CPU-heavy work goes to separate processes or to libraries that release the lock.

On a GPU the word names something much smaller: one lane of a group that executes the same instruction in lockstep inside a streaming multiprocessor, thousands of them at once, scheduled by the GPU's own hardware and never by the operating system's kernel.