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中创建线程有两种方式:函数或者用类来创建线程对象。 函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。 类:创建threading...

轻松掌握python设计模式之策略模式

轻松掌握python设计模式之策略模式

本文实例为大家分享了python策略模式代码,供大家参考,具体内容如下 """ 策略模式 """ import types class StrategyExample: def...

redis之django-redis的简单缓存使用

本文介绍了redis之django-redis的简单缓存使用,分享给大家,具体如下: 自定义连接池 这种方式跟普通py文件操作redis一样,代码如下: views.py impo...

python正则匹配查询港澳通行证办理进度示例分享

复制代码 代码如下:import socketimport re '''广东省公安厅出入境政务服务网护照,通行证办理进度查询。分析网址格式为 http://www.gdcrj.com/w...

python正则表达式修复网站文章字体不统一的解决方法

  网站的大框架下有定义的字体,包括字体大小和颜色等,用户发布文章的时候可能是从其他网站复制过来的文本,复制的过程也保留了字体描述信息。当文章在页面上显示的时候,默认先会使用文章中定义的...