Trying to use threading.local()
Steven D'Aprano wrote:
> 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():
> def attach(value):
# no new local() here
> func.__params__.value = value
> def worker(i):
> print("called from thread %s" % i)
> assert func.__params__.value == i
> value = func.__params__.value
> if value != i:
> print("mismatch", i, value)
func.__params__ = local()
> for i in range(5):
> t = Thread(target=worker, args=(i,))
> 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
> 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?
As I understand it you need one local() instance that is shared by all
workers. Every thead will then see thread-specific values. Once you
overwrite func.__params__ with a new local() in the next worker the data
from the previously initialised worker is lost.