Previously implemented Web servers, the test discovery is actually single-threaded, only one request can be processed at a time, the latter request must wait until the previous request has been processed before entering into the do_* function. In this way when the traffic is larger than the time is not satisfied with the requirements, and later consulted colleagues, told me that threadingmixin this class can implement multi-threaded processing requests. Try it yourself and find that it is possible, and almost no modification, as long as you inherit a parent class in the class that declares the server: Class Securehttpserver (Threadingmixin,httpserver): In the Python source code, ThreadingMixIn This class is in the socketserver.py file, overriding the Process_request function:
def process_request (self, request, client_address): "" "Start a new thread to process the request." " t = Threading. Thread (target = self.process_request_thread, args = (request, client_address)) if self. Daemon_threads:t.setdaemon (1) t.start () #added by Tuochao T.join (10) The last line I added, actually found running for a while After the Python program hangs out, do not know whether and threads are not released. Anyway, after adding this sentence, no longer the program hangs out of the situation. I find it strange that this class does not inherit any parent class, so how does it overwrite the original server class's processing method? To check out the official Python document, in the Socketserver this document introduced a paragraph: these four classes process requests synchronously; Each request must is completed before the next request can be started. This isn ' t suitable if each request takes a long time to complete, because it requires a lot of computation, or because it Returns a lot of data which the client was slow to process. The solution is to create a separate process or thread to handle each request; The Forkingmixin and ThreadingMixIn mix-in classes can be used to support asynchronous behaviour.This paragraph describes the processing mechanism of the default server class, and ThreadingMixIn can indeed provide support for multi-threaded servers. But no introduction is how to do, the source code can not be seen, follow-up study to see it, but threadingmixin this class is really good, as long as the inheritance can be multi-threaded out of the message.
Multi-threaded Web server