Thread
- In Turkish
- iş parçacığı
- Pronunciation
- THRED
In short
A thread is the smallest unit of execution an operating system can schedule, running inside a process and sharing that process's memory with other threads.
What is a thread in programming?
A thread is a single sequence of instructions that the CPU executes. Every process starts with one main thread, and a program can create more threads so that several tasks make progress at the same time, such as downloading a file while keeping the user interface responsive.
Each thread has its own stack, program counter, and register values, but all threads in a process share the same heap memory, global variables, and open files. The operating system scheduler switches between threads, and on a multi-core CPU several threads can run truly in parallel. Because threads share memory, two threads updating the same data at once can cause a race condition, so programs use locks, mutexes, and other synchronization tools to coordinate access.
Think of a process as a shared kitchen and threads as the cooks working in it. The cooks share the same fridge and counter, which makes cooperation fast, but they must take turns with the one sharp knife or they get in each other's way. Threads are used in web servers handling many requests, games that separate rendering from physics, and apps doing work in the background.
Threads are often confused with processes and with asynchronous code. A process has its own isolated memory, while threads inside a process share memory. Asynchronous programming with an event loop, as in Node.js, can juggle many tasks on a single thread by switching between them while they wait for I/O, instead of running them in parallel.
Key takeaways
- A thread is a unit of execution that lives inside a process.
- Threads in the same process share memory, but each has its own stack.
- Multiple threads can run in parallel on a multi-core CPU.
- Shared memory makes race conditions possible, so synchronization such as locks is needed.
- Threads are cheaper to create and switch between than processes.
Example
import threading
def worker(name):
print(f"Thread {name} is running")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(3)]
for t in threads:
t.start() # Begin running worker() in a new thread
for t in threads:
t.join() # Wait for each thread to finish
print("All threads done")Readers ask
What is multithreading?
Multithreading is when a single program uses multiple threads to perform tasks concurrently. It improves responsiveness and can speed up work on multi-core CPUs, but it requires care to avoid race conditions and deadlocks.
Is a thread faster than a process?
Creating and switching between threads is usually cheaper than doing the same with processes, because threads share memory and resources. Processes, however, offer stronger isolation, so a crash in one does not bring down the others.
What is a race condition?
A race condition happens when a program's result depends on the unpredictable timing of threads accessing shared data. It is usually prevented with locks or atomic operations so that only one thread changes the data at a time.
Often compared
See also
- ProcessOperating Systems, p. 23A process is a running instance of a program, with its own memory space, resources, and at least one thread of execution managed by the operating system.
- ConcurrencyProgramming Fundamentals, p. 12Concurrency is a program's ability to make progress on several tasks in overlapping time periods, such as serving many users at once rather than one at a time.
- DeadlockOperating Systems, p. 8A deadlock is a situation where two or more threads or processes wait forever for each other to release resources, so none of them can make progress.
- CPU SchedulingOperating Systems, p. 6CPU scheduling is how an operating system decides which ready process or thread runs on each CPU core next, and for how long, so the processor is shared fairly.
- Event LoopBackend & APIs, p. 13The event loop is a mechanism that lets a single thread handle many tasks by running callbacks one at a time as events and I/O results become ready.
- Async/AwaitProgramming Fundamentals, p. 4Async/await is a syntax for writing asynchronous code that reads like ordinary step-by-step code, pausing at each await until a promise or task finishes.
Spotted a mistake or something missing on this page?Suggest an edit