Junior — Middle
How does memory management differ between threads and processes in Python?
sobes.tech AI
Answer from AI
In Python, threads within a single process share the same memory, meaning all threads have access to the same objects in memory. This facilitates data exchange between threads but requires synchronization to prevent data races.
Processes, on the other hand, have separate address spaces — each process works with its own copy of memory. To exchange data between processes, inter-process communication (IPC) mechanisms such as queues, pipes, or shared memory are used.
Thus, memory management:
- In threads: shared memory, synchronization needed for safety.
- In processes: isolated memory, data exchange through special mechanisms.
Example using the multiprocessing module for data exchange between processes:
from multiprocessing import Process, Queue
def worker(q):
q.put('data from process')
if __name__ == '__main__':
q = Queue()
p = Process(target=worker, args=(q,))
p.start()
print(q.get()) # Receive data from process
p.join()