Question on multiple Python users in one application

Chris Angelico rosuav at gmail.com
Thu Oct 6 22:03:55 EDT 2016


On Fri, Oct 7, 2016 at 12:52 PM, Paul Rubin <no.email at nospam.invalid> wrote:
> "Loren Wilton" <myspamacct at earthlink.net> writes:
>> I've read that Python supports 'threads', and I'd assumed (maybe
>> incorrectly) that these were somewhat separate environments that could
>> be operating concurrently (modulo the GC lock). I assume that data can
>> be shared between the threads,
>
> Threads all run in the same address space.  Data "can be" shared is an
> understatement--it IS shared, so threads can interfere with each other
> very easily.  You have to be quite careful to prevent that, and thread
> programming has a reputation for being difficult for that reason.

To be fair, the sharing of data between threads is no different from
other concerns about global state. The only thing threads change is
that you can have multiple functions doing stuff at once.

state = [1,2,3]

def func():
    state[1] += 5
    # do work
    state[1] -= 5

This function would probably work in most single-threaded
environments. (Proper use of try/finally would make it safer.) This
"patch, operate, unpatch" model becomes dangerous in a threaded
system... but it also becomes dangerous in any case of recursion. Or
just calling a function from inside func() that cares about state. Or
anything like that. Mutable globals must be strictly managed, Alice;
unproductive ones should be *eliminated*.

ChrisA



More information about the Python-list mailing list