Question on multiple Python users in one application

Chris Angelico rosuav at gmail.com
Fri Oct 7 01:10:59 EDT 2016


On Fri, Oct 7, 2016 at 3:06 PM, Loren Wilton <myspamacct at earthlink.net> wrote:
> If the thread has a current instruction pointer, then it must also know what
> function it is currently in, and therfore have a pointer (or some such) to
> the current function locals:
>
> def func1():
>    ham = 0.0;
>    ham += 1;    // thread 1 here
>
> def func2():
>    ham = 0.0;
>    ham -= 1;    // thread 2 here
>
> In my C++ understanding of threads, those manipulations on ham won't
> interact. I would hope this is also true in Python?
>
> If I'm right that a thread knows what function it is in, and therefore has
> function-level state access to the current function, then I'd think that it
> also has to have module level state. After all, functions occur inside
> modules, or at least they can:
>
> spam.py:
> ham = 0.0;
> def func():
>    ham += 1;    // thread 1 here
>
> eggs.py:
> ham = 0.0;
> def func():
>    ham -= 1;    // thread 2 here
>
> Here I would again hope that the simultaneous threads would not cause
> collisions on ham, since (I think?) there should be spam.ham and eggs.ham,
> which would be two separate things.

Correct on both counts. Threads executing different functions cannot
trample on each other's locals. Even if they're executing different
invocations of the same function, they won't trample on locals. With
your module example (assuming you add "global ham" to each function),
they would be fine too; however, if two threads are in two invocations
of the same function, it's possible for them to overwrite each other's
change. (It'd require pinpoint timing, but it could happen.) So if
you're going to use threads, you have to not use mutable global state.
That's honestly not a difficult rule to follow; most programmers
should have a healthy caution around mutable global state anyway,
regardless of threads.

ChrisA



More information about the Python-list mailing list