Trying to use threading.local()

Chris Angelico rosuav at gmail.com
Fri Sep 14 04:43:55 EDT 2018


On Fri, Sep 14, 2018 at 6:34 PM, Thomas Jollans <tjol at tjol.eu> 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:
>>>
>>> On 13-09-18 14:29, Chris Angelico wrote:
>>>>
>>>> "Preferred" doesn't exclude the possibility that alternatives are
>>>> needed, though. For example, good luck making decimal.Decimal contexts
>>>> work correctly without the help of thread-locals - there MIGHT be a
>>>> way to do it, but even if there is, it sure won't be pretty.
>>>
>>> Can you elaborate on that. 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*.
>>
>> ChrisA
>
>
> Ideally use a context manager to manage your context:
> https://docs.python.org/3/library/decimal.html#decimal.localcontext

Which is ALSO setting it "for the active thread", and (at least in the
pure-Python implementation of the decimal module) is implemented on
top of setcontext anyway. Actually, the context manager version
highlights the need for thread-locality even more; you expect
atomicity from it, and you'd be MAJORLY messed up if another thread
broke that.

BTW, to more specifically answer this question:

On Fri, Sep 14, 2018 at 5:25 PM, Antoon Pardon <antoon.pardon at vub.be> wrote:
> If I want my decimal code be usable with threads, how should I write it?

Just write it in the most simple and obvious way. Don't even think
about contexts unless you need to, and if you do, don't concern
yourself with threads and contexts unless you are yourself creating
both of them. Even then, I believe decimal will DTRT by default in
most cases. Thread locals are the magic that makes this happen, but
you don't have to think about that magic usually.

ChrisA



More information about the Python-list mailing list