On 2/15/06, Yang, W (Wanjuan) <[EMAIL PROTECTED]> wrote:
>
> Since the server main thread and child thread will run forever, my question
> is how can I exit the server nicely in the program when it is required (e.g
> no clients coming for a while) rather than using 'Ctrl-c' or kill the process.
>
> another question is: Is that when the main thread is killed, then the child
> thread will stop as well? In this case, before killing the main thread, we
> have to make sure the child thread already finish its job. But how the main
> thread know whether the child thread finish the job or not. in other words,
> how does the main thread communicate the child thread?
>
What Chris said about making the child thread a daemon is right.
Another technique I've found useful when writing threaded servers like
this is to use the timeout facility of sockets (in Python 2.3 onwards)
- you can then have the child thread loop accepting connections *or*
timing out, and checking a run flag to determine when you should stop.
Something like (not tested):
socket.setdefaulttimeout(0.5)
class ServerThread(threading.Thread):
def __init__(self, sock):
threading.Thread.__init__(self)
self.run = True
self.sock = sock
def please_stop(self):
self.run = False
def run(self):
while self.run:
try:
conn, address = self.sock.accept()
# do stuff with connection...
except socket.timeout:
pass # maybe track how many consecutive timeouts?
# any cleanup can go here.
I've found that having the timeout in there makes everything much
easier to handle.
Cheers,
xtian
_______________________________________________
python-uk mailing list
[email protected]
http://mail.python.org/mailman/listinfo/python-uk