[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Trying to use threading.local()

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

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?

Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson