Why my thread can't access the global data?

Antoon Pardon apardon at forel.vub.ac.be
Wed Dec 21 02:55:18 EST 2005


Op 2005-12-21, ddh schreef <doudehou at gmail.com>:
> Hi,
>   I got a problem. I use a 'select' in a loop in the main thread, and
> when select return, a new thread will be created to handle the network
> event. And if the client send some special string, the thread will
> change a global flag to false, so the loop in the main thread will
> break. But it never work.
>
> Below is the code:
> --------------------- s.py (the server) --------------------------
> import socket
> import select
> import thread
> import sys
>
> go_on = True
>
> def read_send(s):
>         s.setblocking(1)
>         str = s.recv(1024)
>         print 'recv:', str
>         s.send(str)
>         s.close()
>         if (str == 'quit'):
>                 go_on = False
>                 print 'User quit...with go_on =', go_on
>         return
>
> [ ... ]

It has nothing to do with threads. If you assign to a name in
a function, that name will be treated as a local variable. So
the go_on = False in read_send will not affect the global go_on.

If you want to rebind global names in a function you have to use
the global statement. So your function would start:


   def read_send(s):
       global go_on
       s.setblocking(1)
       ...

-- 
Antoon Pardon



More information about the Python-list mailing list