Python 多线程实例详解

yipeiwu_com5年前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中的推导式使用详解

推导式是Python中很强大的、很受欢迎的特性,具有语言简洁,速度快等优点。推导式包括: 1.列表推导式 2.字典推导式 3.集合推导式 嵌套列表推导式 NOTE: 字典和集合推导是最近...

python 参数列表中的self 显式不等于冗余

self在区分全局变量/函数和对象中的成员变量/函数十分有用。例如,它提供了一种作用域机制,我个人认为比Ruby的@和@@清晰多了,这可能是习惯使然吧,但它确实和C++、Java中的th...

python pandas.DataFrame选取、修改数据最好用.loc,.iloc,.ix实现

相信很多人像我一样在学习python,pandas过程中对数据的选取和修改有很大的困惑(也许是深受Matlab)的影响。。。 到今天终于完全搞清楚了!!! 先手工生出一个数据框吧 i...

Python基于列表模拟堆栈和队列功能示例

本文实例讲述了Python基于列表模拟堆栈和队列功能。分享给大家供大家参考,具体如下: 之前的文章/post/59897.htm介绍了堆栈与队列的Python实现方法,这里使用列表来模拟...

python实现简单聊天室功能 可以私聊

python实现简单聊天室功能 可以私聊

本文实例为大家分享了python实现简单聊天室功能的具体代码,供大家参考,具体内容如下 公共模块 首先写一个公共类,用字典的形式对数据的收发,并且进行封装,导入struct解决了TCP的...