Why my thread can't access the global data?

2005-12-20 Thread ddh
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


s = socket.socket(socket.AF_INET)
s.bind(('', ))
s.listen(5)
s.setblocking(0)

while go_on:
r_set = [s.fileno(),]
r, w, e = select.select(r_set,[],[],0.5)
print 'select returned with go_on =', go_on
for rs in r:
if rs == s.fileno():
ns, addr = s.accept()
print 'socket on', addr, 'has been accepted'
thread.start_new_thread(read_send, (ns,))
s.close()


- c.py (the client) --
import socket
import sys

if len(sys.argv) != 3:
print 'usage: python c.py ip port'
sys.exit(-1)

ip = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET)
s.settimeout(5)
s.connect((ip, port))
str = raw_input('please input:')
s.send(str)
str = s.recv(1024)
print 'received:', str
s.close()

--
run s.py first, and then run c.py as:
python c.py 127.0.0.1 
and then input 'quit', but the server never end :(



Thank you for your help!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why my thread can't access the global data?

2005-12-20 Thread ddh
Thank you, but I think it may be not this reason.

You see, when accept returns, the go_on will be checked in 'while
go_on:', so if it is set to be false, the loop will end. I have set a
0.5 second time out on the select() function. So the 'go_on' will be
checked at a frequency every 0.5 second at least.




Pelmen wrote:
> your main loop already on accept when your thread change the go_on imho
> try to input another string after 'quit'
> 
> and actually there is no need to use thread

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why my thread can't access the global data?

2005-12-21 Thread ddh
Thank you very much.
I am a newbie for python :-)


Antoon Pardon wrote:
>
> 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

-- 
http://mail.python.org/mailman/listinfo/python-list