How to exit from a thread that is waiting on a blocking socket call?
I am trying to do something along the following lines, as the main thread for a
simplified SMTP server:
try:
s = socket(AF_INET, SOCK_STREAM) # create socket
s.bind(host, port) # attempt to bind to address/port
except:
print 'Unable to bind host', host, 'to port', port
else:
s.listen(5) # allow up to 5 queued connections
server_running = 1
while (server_running):
print 'Server waiting for connection'
connection, client_address = s.accept() # blocking call
create_session(connection, client_address) # sets a thread running to
handle the SMTP session
sleep(5)
sef_lock.acquire()
if server_exit_flag == 1:
server_running = 0
sef_lock.release()
# never gets here because accept() is a blocking call, and get Winsock error
if try to change socket mode to
# non-blocking
print 'Waiting for all sessions to complete'
all_done = 0
while (not all_done):
ad_flag.acquire()
if running == 0:
all_done = 1
ad_flag.release()
print 'All sessions completed - server exiting'
The problem I have is not being able to exit the main loop - accept() blocks
waiting for a new connection, and if I set the socket mode to non-blocking (I
had to do this in the session code in order to be able to implement a timeout)
then accept() fails with winsock error 10035.
Any suggestions? Platform is NT 4.0.
Richard