Senior
What is the difference between threads and processes?
sobes.tech AI
Answer from AI
A process is an isolated execution unit with its own address space, resources, and memory. A thread is a lighter-weight unit that exists within a process and shares memory and resources with other threads of the same process.
Main differences:
- Isolation: processes are isolated from each other, threads are not.
- Memory: processes have separate address spaces, threads share the process's memory.
- Creation and switching: creating and switching between threads is faster and cheaper than between processes.
- Data exchange: it is easier for threads to exchange data via shared memory, while for processes it is more complex (via IPC).
Example in Python:
import threading
import multiprocessing
def worker():
print('Working')
# Thread
thread = threading.Thread(target=worker)
thread.start()
# Process
process = multiprocessing.Process(target=worker)
process.start()