- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver_thread.py
More file actions
Latest commit
46 lines (39 loc) · 1.06 KB
/
Copy pathserver_thread.py
File metadata and controls
46 lines (39 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
importjson
importtime
importflask
fromconcurrent.futuresimportThreadPoolExecutor
app=flask.Flask(__name__)
pool=ThreadPoolExecutor()
defread_file():
time.sleep(0.1) # 模拟I/O操作
return'file result'
defread_db():
time.sleep(0.2) # 模拟I/O操作
return'db result'
defread_api():
time.sleep(0.3) # 模拟I/O操作
return'api result'
# 使用单线程,耗时6s+
# @app.route("/")
# def index():
# result_file = read_file()
# result_db = read_db()
# result_api = read_api()
# return json.dumps({
# "result_file": result_file.result(),
# "result_db": result_db.result(),
# "result_api": result_api.result()
# })
# 使用多线程,耗时3s+
@app.route("/")
defindex():
result_file=pool.submit(read_file)
result_db=pool.submit(read_db)
result_api=pool.submit(read_api)
returnjson.dumps({
"result_file": result_file.result(),
"result_db": result_db.result(),
"result_api": result_api.result()
})
if__name__=='__main__':
app.run()