Junior
What is the difference between a process and a thread?
sobes.tech AI
Answer from AI
A process is an independent, isolated unit of program execution with its own address space and resources (file descriptors, memory). Creating and switching between processes is more costly.
A thread (or thread) is a lighter unit of execution within a single process. Threads share the same address space and process resources. Creating and switching between threads is cheaper.
| Characteristic | Process | Thread |
|---|---|---|
| Address space | Independent | Shared |
| Isolation | Strong | Weak (within a process) |
| Creation/Destruction | Costly | Cheap |
| Context switching | Costly | Cheap |
| Data exchange | Via IPC (Inter-Process Communication) | Easy (shared memory), requires synchronization |
| Fault tolerance | Failure of one does not affect others | Failure of one can affect the entire process |
| Scheduling | By the operating system | By the operating system (or thread scheduler) |
Example of creating a process in Python:
import multiprocessing
def worker():
# Code executed in a separate process
print("Worker process")
if __name__ == "__main__":
p = multiprocessing.Process(target=worker)
p.start()
p.join() # Wait for process to finish
Example of creating a thread in Python:
import threading
def worker():
# Code executed in a separate thread
print("Worker thread")
if __name__ == "__main__":
t = threading.Thread(target=worker)
t.start()
t.join() # Wait for thread to finish