server.py
- import time
- import tornado.web
- import tornado.gen
- import tornado.ioloop
- from tornado import httpserver
- from tornado.concurrent import run_on_executor
- from concurrent.futures import ThreadPoolExecutor
-
- class SyncHandler(tornado.web.RequestHandler):
-
- def get(self, *args, **kwargs):
- print("begin sync.")
- time.sleep(5)
- self.write("sync handler, hello.")
-
-
- class AsyncHandler(tornado.web.RequestHandler):
-
- executor = ThreadPoolExecutor(5)
-
- @tornado.gen.coroutine
- def get(self):
- print("begin async.")
- result = yield self.core_process()
- self.write(result)
-
- @run_on_executor()
- def core_process(self):
- time.sleep(5)
- return 'asyn handler, hello.'
-
-
- class Application(tornado.web.Application):
- def __init__(self):
- handlers = [
- (r'/sync', SyncHandler),
- (r'/async', AsyncHandler)
- ]
- settings = dict(
- debug=True,
- template_path="templates",
- static_path="static"
- )
- super(Application, self).__init__(handlers, **settings)
-
-
- application = Application()
-
- if __name__ == "__main__":
-
- http_server = httpserver.HTTPServer(application)
- http_server.listen(10002)
- http_server.start(1) #启动进程数,window下只能是1
- tornado.ioloop.IOLoop.instance().start()
client.py
使用tomorrow模拟多线程并发访问
- import requests
- import time
- from tomorrow import threads
-
-
- @threads(10)
- def sync_test():
- payload = {}
- headers = {}
- response = requests.request("GET", 'http://127.0.0.1:10002/sync', headers=headers, data=payload)
- print(response.text + ' ' + time.strftime('%H:%M:%S'))
-
- @threads(10)
- def async_test():
- payload = {}
- headers = {}
- response = requests.request("GET", 'http://10.1.15.24:10002/async', headers=headers, data=payload)
- print(response.text + ' ' + time.strftime('%H:%M:%S'))
-
-
-
- [sync_test() for i in range(100)]
- # [async_test() for i in range(50)]
-
同步输出结果,每5s只能处理一个请求
看以看到,10线程请求同步接口时候,是每隔5秒才能领处理完成一个请求。程序中设置的tornado进程是1,如果把tornado服务的进程数量提高为4,每5秒也能处理4个同步请求。
异步处理输出结果:

看以看到,10线程请求异步接口时候,是每隔5秒能处理5个请求,因为代码中设置的ThreadPoolExecutor(5)数量是5。如果设置为8,那么每5秒可以处理8个请求。
问题:对于异步处理和同步处理,同一个时间段发起的10个线程请求剩下的5个线程请求在下一个5秒是接着处理,还是丢弃了?