码迷,mamicode.com
首页 > 编程语言 > 详细

多线程的web服务器

时间:2015-06-15 20:16:19      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

之前实现的web服务器,经测试发现实际上是单线程的,每次只能处理一个请求,后一个请求必须要等前一个请求处理完后才能进入到do_*函数中。这样在访问量比较大的时候是不能满足要求的,后来请教了一下同事,告诉我说ThreadingMixIn这个类可以实现多线程处理请求。自己去试了一下,发现果然可以,而且几乎不用做任何修改,只要在声明server的类中多继承一个父类就行:
class SecureHTTPServer(ThreadingMixIn,HTTPServer):

在python源代码中ThreadingMixIn这个类是在SocketServer.py文件中,重写了process_request这个函数:
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) 最后一行是我加的,实际中发现运行一段时间后会出现python程序挂掉的情况,不知道是否和线程没有释放有关。反正加了这句后,没有再出现程序挂掉的情况。 我觉得奇怪的是,这个类没有继承任何父类,那么它是怎么覆盖掉原来server类的处理方法的?去查了下python的官方文档,在SocketServer这个文件的介绍中有这样一段话: These four classes process requests synchronously; each request must be 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 is 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. 这段话介绍了默认server类的处理机制,以及ThreadingMixIn确实可以提供多线程服务器的支持。但是没有介绍是如何做到的,源代码里也看不出来,后续再研究看看吧,不过ThreadingMixIn这个类确实好用,只要继承一下就可以多线程出来消息了。

多线程的web服务器

标签:

原文地址:http://www.cnblogs.com/tuochao/p/4578988.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!