On Wed, Sep 12, 2018 at 06:59:44AM -0700, Ethan Furman wrote:
> On 09/12/2018 05:17 AM, Steven D'Aprano wrote:
[...]
> >We could solve this race condition with locking, or by making the pair
> >of steps:

[...]
> >I'm not an expert on threaded code, so it is possible I've missed some
> >non-obvious fix for this, but I expect not. In general, solving race
> >conditions without deadlocks is a hard problem.
> 
> I believe the solution is `threading.local()`, and Python would 
> automatically use it in these situations.

I'm finding it hard to understand the documentation for 
threading.local():

https://docs.python.org/3/library/threading.html#threading.local

as there isn't any *wink* although it does refer to the docstring of a 
private implementation module. But I can't get it to work. Perhaps I'm 
doing something wrong:


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'


In any case, if Steve Barnes didn't actually intend for the __params__ 
to be attached to the function object as an externally visible 
attribute, the whole point is moot.



-- 
Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to