多线程通常是新开一个后台线程去处理比较耗时的操作,Python做后台线程处理也是很简单的,今天从官方文档中找到了一个Demo.
import threading, zipfile
class AsyncZip(threading.Thread):
def __init__(self, infile, outfile):
threading.Thread.__init__(self)
self.infile = infile
self.outfile = outfile
def run(self):
f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
f.write(self.infile)
f.close()
print('Finished background zip of:', self.infile)
background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print('The main program continues to run in foreground.')
background.join() # Wait for the background task to finish
print('Main program waited until background was done.')结果:
The main program continues to run in foreground.
Finished background zip of: mydata.txt
Main program waited until background was done.
Press any key to continue . . .
本文介绍如何利用Python的多线程特性,通过创建后台线程异步执行压缩任务,确保主程序流畅运行。具体展示了通过定义自定义线程类`AsyncZip`来实现文件异步压缩,并在主线程中处理后续逻辑。
1702

被折叠的 条评论
为什么被折叠?



