Trying to use threading.local()
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Wed Sep 12 12:16:05 EDT 2018
I'm originally posted this on the Python-Ideas list, but this is probably
more appropriate.
import time
from threading import Thread, local
def func():
pass
def attach(value):
func.__params__ = local()
func.__params__.value = value
def worker(i):
print("called from thread %s" % i)
attach(i)
assert func.__params__.value == i
time.sleep(3)
value = func.__params__.value
if value != i:
print("mismatch", i, value)
for i in range(5):
t = Thread(target=worker, args=(i,))
t.start()
print()
When I run that, each of the threads print their "called from ..."
message, the assertions all pass, then a couple of seconds later they
consistently all raise exceptions:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/threading.py", line 914, in
_bootstrap_inner
self.run()
File "/usr/local/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "<stdin>", line 5, in worker
AttributeError: '_thread._local' object has no attribute 'value'
What am I doing wrong?
--
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson
More information about the Python-list
mailing list