CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example19.py
Views: 729
1
"""
2
扩展性系统性能
3
- 垂直扩展 - 增加单节点处理能力
4
- 水平扩展 - 将单节点变成多节点(读写分离/分布式集群)
5
并发编程 - 加速程序执行 / 改善用户体验
6
耗时间的任务都尽可能独立的执行,不要阻塞代码的其他部分
7
- 多线程
8
1. 创建Thread对象指定target和args属性并通过start方法启动线程
9
2. 继承Thread类并重写run方法来定义线程执行的任务
10
3. 创建线程池对象ThreadPoolExecutor并通过submit来提交要执行的任务
11
第3种方式可以通过Future对象的result方法在将来获得线程的执行结果
12
也可以通过done方法判定线程是否执行结束
13
- 多进程
14
- 异步I/O
15
"""
16
import glob
17
import os
18
import time
19
20
from concurrent.futures import ThreadPoolExecutor
21
from threading import Thread
22
23
from PIL import Image
24
25
26
# class ThumbnailThread(Thread):
27
28
# def __init__(self, infile):
29
# self.infile = infile
30
# super().__init__()
31
32
# def run(self):
33
# file, ext = os.path.splitext(self.infile)
34
# filename = file[file.rfind('/') + 1:]
35
# for size in (32, 64, 128):
36
# outfile = f'thumbnails/{filename}_{size}_{size}.png'
37
# image = Image.open(self.infile)
38
# image.thumbnail((size, size))
39
# image.save(outfile, format='PNG')
40
41
42
def gen_thumbnail(infile):
43
file, ext = os.path.splitext(infile)
44
filename = file[file.rfind('/') + 1:]
45
for size in (32, 64, 128):
46
outfile = f'thumbnails/{filename}_{size}_{size}.png'
47
image = Image.open(infile)
48
image.thumbnail((size, size))
49
image.save(outfile, format='PNG')
50
51
52
# def main():
53
# start = time.time()
54
# threads = []
55
# for infile in glob.glob('images/*'):
56
# # t = Thread(target=gen_thumbnail, args=(infile, ))
57
# t = ThumbnailThread(infile)
58
# t.start()
59
# threads.append(t)
60
# for t in threads:
61
# t.join()
62
# end = time.time()
63
# print(f'耗时: {end - start}秒')
64
65
66
def main():
67
pool = ThreadPoolExecutor(max_workers=30)
68
futures = []
69
start = time.time()
70
for infile in glob.glob('images/*'):
71
# submit方法是非阻塞式的方法
72
# 即便工作线程数已经用完,submit方法也会接受提交的任务
73
future = pool.submit(gen_thumbnail, infile)
74
futures.append(future)
75
for future in futures:
76
# result方法是一个阻塞式的方法 如果线程还没有结束
77
# 暂时取不到线程的执行结果 代码就会在此处阻塞
78
future.result()
79
end = time.time()
80
print(f'耗时: {end - start}秒')
81
# shutdown也是非阻塞式的方法 但是如果已经提交的任务还没有执行完
82
# 线程池是不会停止工作的 shutdown之后再提交任务就不会执行而且会产生异常
83
pool.shutdown()
84
85
86
if __name__ == '__main__':
87
main()
88
89
90
91
92
93
94
95
96