osdir.com


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

Trying to use threading.local()


Chris Angelico wrote:

> On Thu, Sep 13, 2018 at 10:22 PM, Peter Otten <__peter__ at web.de> wrote:
>> Antoon Pardon wrote:
>>
>>> On 12-09-18 22:14, Peter Otten wrote:
>>>> As I understand it you need one local() instance that is shared by all
>>>> workers. Every thead will then see thread-specific values.
>>>
>>> It has always puzzled me how this is useful. The times I work with
>>> threads, I just put thread specific values in the local variables of the
>>> thread function.
>>
>> That would be my preferred approach, too. Passing around variables
>> through multiple levels of function calls may be inconvenient, but global
>> variables tend to cause more trouble in the long run.
> 
> "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.

I'm outside my comfort zone with both threads and decimal, but it appears 
that you can pass the context explicitly. So

getcontext().prec = 10
a = Decimal(1)  # magically determine context
b = Decimal(3)

might become

context = Context(prec=10)
a = Decimal(1, context=context)
b = Decimal(3, context=context)

However, the trouble begins with

a/b  # magically determine context

which has no way to smuggle in a third argument. The workaround while not 
pretty is at least straightforward:

context.divide(a, b)