How to use two threads (GUI and backend)
Chris Angelico
rosuav at gmail.com
Wed Oct 26 09:51:32 EDT 2016
On Thu, Oct 27, 2016 at 12:37 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Chris Angelico <rosuav at gmail.com>:
>
>> On Wed, Oct 26, 2016 at 11:58 PM, Marko Rauhamaa <marko at pacujo.net> wrote:
>>> I can't think of a valid program that could take advantage of this
>>> primitive guarantee of Python's. For example, there is no "volatile"
>>> in Python so you can't coordinate Python threads safely without
>>> proper synchronization. If you set a variable in one thread and read
>>> it in another thread, the latter might never see the change.
>>
>> Incorrect. If you set something in one thread and read it in another,
>> it WILL see it, just as it would with any other way of running two
>> functions. (Obviously function locals won't be seen, because they
>> never will.) Global state is shared across all threads.
>
> I don't know what "Global state is shared across all threads" means in
> this context. It sounds like something that would be true for, say, Java
> and C as well. However, those languages don't promise to propagate
> improperly synchronized changes between threads.
>
> Now I would like to ask for some documentation.
Here you have two functions and a global:
active = True
def func1():
while active:
# do work
time.sleep(1)
func2()
def func2():
global active
if random.random() < 0.1:
active = False
I'm sure you understand that these functions share the global state of
the 'active' flag. One changes it, the other sees the change. So far,
nothing controversial or difficult.
It's exactly the same with threads. If you remove the func2() call
from func1 and have it operate on a separate thread, and then call
func2 from the main thread (or another secondary thread), func1 will
notice the change the very next time it gets to the top of the loop.
The two functions are executing in the same process, the same module,
the same everything except their call stack (ie locals).
ChrisA
More information about the Python-list
mailing list