osdir.com


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

Trying to use threading.local()


On Fri, Sep 14, 2018 at 7:18 PM, Antoon Pardon <antoon.pardon at vub.be> wrote:
> On 14-09-18 10:29, Chris Angelico wrote:
>> On Fri, Sep 14, 2018 at 5:25 PM, Antoon Pardon <antoon.pardon at vub.be> wrote:
>>>
>>> ... Suppose I have two threads, one in which I need
>>> a precision of 3 and the other in which I need a precision of 7. In what
>>> circumstances is it needed to use threads-locals to accomplish this and
>>> how do I accomplish this?
>>>
>>> If I want my decimal code be usable with threads, how should I write it?
>> Let's say both of those threads call the same function, which does this:
>>
>> def f(x, y):
>>     return x * 3 + y / 4
>>
>> You can't pass a context as a parameter, so you have to set the
>> context externally. Which is done thus:
>>
>> https://docs.python.org/3/library/decimal.html#decimal.setcontext
>>
>> Note that this sets it *for the current thread*.
>
> So, if I understand correctly, the threads-local information in this case is
> part of the decimal implementation, so that the right context/precision is
> used for the right thread.
>

Correct, though it's an exposed part of the API too, so it's not
"implementation detail" in the sense that it could be changed easily.

ChrisA