Programs often have to do several things at once: serve many clients, call slow services, use many CPU cores. Operating systems and languages offer three main tools.
Processes
A process is a running program with its own memory. Processes are isolated: a crash or a memory bug in one does not corrupt another. They communicate through explicit channels such as pipes, sockets or shared files. They are heavier to create than threads and sharing data costs copying.
Threads
Threads run inside one process and share its memory. They are cheaper than processes and can exchange data directly, which is also the danger. Two threads changing the same value without coordination cause a race condition: the result depends on timing.
import threading
counter = 0
lock = threading.Lock()
def work():
global counter
for _ in range(10_000):
with lock: # without the lock, updates can be lost
counter += 1
threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(counter) # 40000Locks fix races but bring their own problems: a deadlock happens when two threads each hold a lock the other needs. Prefer passing messages or using immutable data over sharing and locking.
Async I/O and event loops
Much of a server's time is waiting for the network or disk. With async I/O, one thread runs an event loop: when a task would wait, it hands control back, and the loop runs another task until the awaited result is ready. Thousands of connections can be handled by one thread, with no locks for data confined to the loop. The price is that any long computation, or blocking call, stalls every task.
Choosing
- CPU-bound work (image processing, number crunching): use multiple processes or threads that truly run in parallel. Note that some languages, for example CPython, restrict parallel execution of threads for pure code, so processes are used instead.
- I/O-bound work (web servers, API clients): async I/O or threads, both work well.
- Isolation and reliability: processes.
Takeaway
Processes isolate, threads share and async waits efficiently. Choose by the kind of work, keep shared state small and avoid blocking calls inside an event loop.
Comments