Last active
October 30, 2024 09:32
-
-
Save tiagocoutinho/5dd7dfd0af63e8fedb7542e5a2fefbbb to your computer and use it in GitHub Desktop.
Python thread pitfall
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is no longer unsafe at least with CPython 3.11, but this variant is: