Skip to content

Instantly share code, notes, and snippets.

@pitrk
Created September 23, 2018 22:30
Show Gist options
  • Save pitrk/95d348267ef7e1102b0e5e07981f2b23 to your computer and use it in GitHub Desktop.
Save pitrk/95d348267ef7e1102b0e5e07981f2b23 to your computer and use it in GitHub Desktop.
Is class attribute shared between threads in Python?
import threading
class SharingChecker:
number: int = 0
def increment(self) -> None:
SharingChecker.number += 1
def task() -> None:
s = SharingChecker()
s.increment()
print(s.number)
pcs = []
for thread in range(5):
pcs.append(threading.Thread(target=task))
for thread in pcs:
thread.start()
thread.join()
"""
Is class attribute shared between threads in Python?
output:
1
2
3
4
5
Conclusion: Yes, it is.
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment