0

I'm implementing an HTTP server using python BaseHttpServer.

I have a queue that is shared by different threads. And each time my handler receives a request, it puts it into the shared queue. When the number of requests in queue reaches n, I'd like to shutdown the server. Here's what I have right now:

while self.queue.qsize() != n
     self.server.handle_request()

My concern about this approach is that, it is possible that when checking self.queue.qsize() it's not yet n, but after that the size becomes n immediately (because the queue is shared by multiple threads) and there's no following requests anymore. Given that server.handle_request() blocks if there is no requests, the server may shutdown anymore. Is there a way to solve this problem?

1 Answer 1

0

Bind a thread to the process:

httpd = BaseHTTPServer.HTTPServer(('', 80), MyHandler)
print("Starting server in thread")
threading.Thread(target=httpd.serve_forever).start()

Shutting Down:

toKill = threading.Event()

# in handler
toKill.set()

# in main thread
toKill.wait()
httpd.shutdown()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.