脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 多线程实例详解

Python 多线程实例详解

2020-09-25 10:29Python教程网 Python

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

Python 多线程实例详解

多线程通常是新开一个后台线程去处理比较耗时的操作,Python做后台线程处理也是很简单的,今天从官方文档中找到了一个Demo.

实例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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.')

结果:

?
1
2
3
4
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 . . .

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/afandaafandaafanda/article/details/45952875

延伸 · 阅读

精彩推荐