使用python多线程实例详解

这篇文章主要介绍了python 多线程实例详解的相关资料,需要的朋友可以参考下

python 多线程实例详解

多线程通常是新开一个后台线程去处理比较耗时的操作,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多线程实例详解的详细内容,更多请关注 第一php社区 其它相关文章!

Posted in 未分类