Threads vs Processes in Python

After a late night of debugging, we are rudely reminded that threads are different from processes in the way that they handle changes to variables passed as arguments.

from multiprocessing import Process
from sys import argv
from threading import Thread


class X:
    a = 1


def f(o):
    o.a = 2


W = Thread if argv[1] == 'thread' else Process


x = X()
w = W(target=f, args=(x,))
print(x.a)
w.start()
w.join()
print(x.a)

Specifically, thread variables are shared while process variables are copied.

$ python thr.py thread
1
2

$ python thr.py process
1
1

This means that changes to variables passed as arguments to threads are reflected both inside and outside the thread.

In contrast, changes to variables passed as arguments to processes are independent inside vs outside the process because the variables inside the process are actually copies and not the original variables themselves.