Skip to content

Instantly share code, notes, and snippets.

@tiagocoutinho
Last active October 30, 2024 09:32
Show Gist options
  • Save tiagocoutinho/5dd7dfd0af63e8fedb7542e5a2fefbbb to your computer and use it in GitHub Desktop.
Save tiagocoutinho/5dd7dfd0af63e8fedb7542e5a2fefbbb to your computer and use it in GitHub Desktop.
Python thread pitfall
# I dare you to find an execution that prints out 0
# (at least using the CPython implementation)
from threading import Thread
C, N = 0, 1_000_000
def f(inc=1):
global C, N
for i in range(N):
C += inc
ths = Thread(None, f, (1,)), Thread(None, f, (-1,))
[th.start() for th in ths]
[th.join() for th in ths]
print(C)
@cpascual
Copy link

cpascual commented Oct 30, 2024

This is no longer unsafe at least with CPython 3.11, but this variant is:

import time
from threading import Thread

C, N = 0, 1000

def f(inc):
    global C, N
    for i in range(N):
        a = C
        time.sleep(0.001)
        C = a + inc


th1 = Thread(target=f, args=(-1,))
th2 = Thread(target=f, args=(1,))
th1.start()
th2.start()
th1.join()
th2.join()
print(C)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment