Last active
February 5, 2018 20:30
-
-
Save mortymacs/01b7a945b32e8913406dfe986c802743 to your computer and use it in GitHub Desktop.
Thread-Specific State in Python
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
[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 |
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
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch12s06.html