CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Day16-20/code/example19.py
Views: 729
"""1扩展性系统性能2- 垂直扩展 - 增加单节点处理能力3- 水平扩展 - 将单节点变成多节点(读写分离/分布式集群)4并发编程 - 加速程序执行 / 改善用户体验5耗时间的任务都尽可能独立的执行,不要阻塞代码的其他部分6- 多线程71. 创建Thread对象指定target和args属性并通过start方法启动线程82. 继承Thread类并重写run方法来定义线程执行的任务93. 创建线程池对象ThreadPoolExecutor并通过submit来提交要执行的任务10第3种方式可以通过Future对象的result方法在将来获得线程的执行结果11也可以通过done方法判定线程是否执行结束12- 多进程13- 异步I/O14"""15import glob16import os17import time1819from concurrent.futures import ThreadPoolExecutor20from threading import Thread2122from PIL import Image232425# class ThumbnailThread(Thread):2627# def __init__(self, infile):28# self.infile = infile29# super().__init__()3031# def run(self):32# file, ext = os.path.splitext(self.infile)33# filename = file[file.rfind('/') + 1:]34# for size in (32, 64, 128):35# outfile = f'thumbnails/{filename}_{size}_{size}.png'36# image = Image.open(self.infile)37# image.thumbnail((size, size))38# image.save(outfile, format='PNG')394041def gen_thumbnail(infile):42file, ext = os.path.splitext(infile)43filename = file[file.rfind('/') + 1:]44for size in (32, 64, 128):45outfile = f'thumbnails/{filename}_{size}_{size}.png'46image = Image.open(infile)47image.thumbnail((size, size))48image.save(outfile, format='PNG')495051# def main():52# start = time.time()53# threads = []54# for infile in glob.glob('images/*'):55# # t = Thread(target=gen_thumbnail, args=(infile, ))56# t = ThumbnailThread(infile)57# t.start()58# threads.append(t)59# for t in threads:60# t.join()61# end = time.time()62# print(f'耗时: {end - start}秒')636465def main():66pool = ThreadPoolExecutor(max_workers=30)67futures = []68start = time.time()69for infile in glob.glob('images/*'):70# submit方法是非阻塞式的方法71# 即便工作线程数已经用完,submit方法也会接受提交的任务72future = pool.submit(gen_thumbnail, infile)73futures.append(future)74for future in futures:75# result方法是一个阻塞式的方法 如果线程还没有结束76# 暂时取不到线程的执行结果 代码就会在此处阻塞77future.result()78end = time.time()79print(f'耗时: {end - start}秒')80# shutdown也是非阻塞式的方法 但是如果已经提交的任务还没有执行完81# 线程池是不会停止工作的 shutdown之后再提交任务就不会执行而且会产生异常82pool.shutdown()838485if __name__ == '__main__':86main()87888990919293949596