Skip to content

Instantly share code, notes, and snippets.

@mortymacs
Last active February 5, 2018 20:30
Show Gist options
  • Save mortymacs/01b7a945b32e8913406dfe986c802743 to your computer and use it in GitHub Desktop.
Save mortymacs/01b7a945b32e8913406dfe986c802743 to your computer and use it in GitHub Desktop.
Thread-Specific State in Python
[morteza@ipo ~]$ python sample.py
Traceback (most recent call last):
File "sample.py", line 29, in <module>
print(s[2].p())
File "sample.py", line 11, in p
print(self.local.name)
AttributeError: '_thread._local' object has no attribute 'name'
[morteza@ipo ~]$ python sample.py
Traceback (most recent call last):
File "sample.py", line 29, in <module>
print(s[2].p())
File "sample.py", line 11, in p
print(self.local.name)
AttributeError: '_thread._local' object has no attribute 'name'
[morteza@ipo ~]$ python sample.py
140333562648320 Private
140333554255616 Private
140333543466752 Private
140333562648320 Private
140333543466752 Private
140333562648320 Private
140333543466752 Private
140333562648320 Private
140333562648320 Private
140333543466752 Private
Public
import time
import threading
# main class
class x:
def __init__(self):
self.local = threading.local() # <<< thread-specific data
self.name = "Public"
self.local.name = "Private"
self.p()
def p(self):
print(threading.current_thread().ident, self.local.name)
# update list of instances by different threads
def y(s):
s.append(x())
# spawn threads
t = []
s = []
for i in range(10):
tmp = threading.Thread(target=y, args=(s,))
t.append(tmp)
tmp.start()
time.sleep(2)
# access to public variable
print(s[2].name)
# error lines
# print(s[2].local.name) <<< could not access to name because of different thread
# print(s[2].p()) <<< could not access to name because of different thread
# release threads
for i in t:
i.join()
@mortymacs
Copy link
Author

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