Trying to use threading.local()

Peter Otten __peter__ at web.de
Wed Sep 12 16:14:02 EDT 2018


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():
>     pass
> 
> def attach(value):
      # no new local() here
>     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)

  func.__params__ = local()
> 
> 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?

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.






More information about the Python-list mailing list