Reputation: 351
I have the following code. I have a server that has a work queue. Worker clients will connect to this server. Once they're connected, they'll be sent off to a separate thread where they will be assigned work. This thread will repeatedly assign work until the queue is empty. Once the queue is empty, both the thread and the client will exit.
My problem is that, the main thread also should shutdown once the work queue is done. I cannot get it to do so. The main thread so far looks like follows:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(),port))
s.listen()
thread_list = list()
while(True):
if(not work_queue.empty()):
conn, addr = s.accept()
else:
for thread in thread_list:
thread.join()
print('Program done. Bye!')
break
print('Accepted a connection from '+str(addr))
new_thread = threading.Thread(target=assign_task, args=(conn, addr))
thread_list.append(new_thread)
new_thread.start()
My main thread gets stuck at accept even if I check for queue empty. How do I get it to shutdown when the work queue is empty?
Any help is appreciated.
Upvotes: 0
Views: 137
Reputation: 106
Try using settimeout(). You can set the socket timeout to however long you want in seconds, and when nothing connects to the server in that set time, it will throw an error. Then you can use try/except to break out of the code. It could be done like so:
if(work_queue.empty()):
s.settimeout(10) #set timeout to 10 seconds if work_queue.empty() returns true
try:
conn, addr = s.accept()
except socket.timeout: #if the socket times out
for thread in thread_list:
thread.join()
print('Program done. Bye!')
break
This, of course, would be inside your main loop, replacing your current if/else statement
Upvotes: 0