Python 多线程实例详解

yipeiwu_com6年前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写“猜数字”,“猜词语”,“谁是卧底”这三个游戏,从而快速掌握python编程的入门知识,包括python语法/列表/元组/字典/流程控制/库函数等等。 环境参...

PyQt5下拉式复选框QComboCheckBox的实例

PyQt5下拉式复选框QComboCheckBox的实例

笔者在用PyQt5写GUI时碰到了需要使用下拉式复选框的情况,但是PyQt5中没有相应的组件,而网上找到的方法大多是qt使用的,所以不能直接拿来用。 没办法,在这种让人无奈的情况下,笔者...

pygame实现俄罗斯方块游戏(基础篇2)

pygame实现俄罗斯方块游戏(基础篇2)

接上章《pygame实现俄罗斯方块游戏(基础篇1)》继续写俄罗斯方块游戏 五、计算方块之间的碰撞 在Panel类里增加函数 def check_overlap(self, diffx...

如何使用七牛Python SDK写一个同步脚本及使用教程

如何使用七牛Python SDK写一个同步脚本及使用教程

七牛云存储的 Python 语言版本 SDK(本文以下称 Python-SDK)是对七牛云存储API协议的一层封装,以提供一套对于 Python 开发者而言简单易用的开发工具。Pytho...

Python深入学习之对象的属性

Python一切皆对象(object),每个对象都可能有多个属性(attribute)。Python的属性有一套统一的管理方案。 属性的__dict__系统 对象的属性可能来自于其类定义...