python多线程用法实例详解


Posted in Python onJanuary 15, 2015

本文实例分析了python多线程用法。分享给大家供大家参考。具体如下:

今天在学习尝试学习python多线程的时候,突然发现自己一直对super的用法不是很清楚,所以先总结一些遇到的问题。当我尝试编写下面的代码的时候:

class A():

    def __init__( self ):

        print "A"

class B( A ):

    def __init__( self ):

        super( B, self ).__init__(  )

# A.__init__( self )

        print "B"

b = B()

出现:

super( B, self ).__init__()

TypeError: must be type, not classobj

最后发现原来是python中的新式类的问题,也就是A必须是新式类。解决方法如下两种:

(1)

class A( object ):

    def __init__( self ):

        print "A"

class B( A ):

    def __init__( self ):

        super( B, self ).__init__(  )

# A.__init__( self )       ##这条语句是旧式的,存在潜在的问题,应该避免使用

        print "B"

b = B()

(2)

__metaclass__=type

class A():

    def __init__( self ):

        print "A"

class B( A ):

    def __init__( self ):

        super( B, self ).__init__(  )

# A.__init__( self )    ##这条语句是旧式的,存在潜在的问题,应该避免使用

        print "B"

b = B()

注意:如果在super( B, self ).__init__(  )

语句中添加self,也就是super( B, self ).__init__( self ),会出现如下的错误:

    super( B, self ).__init__( self )

TypeError: __init__() takes exactly 1 argument (2 given)

以上只是一点点本人的心得笔记,呵呵。

import threading, time

class myThread( threading.Thread ):

    def __init__( self, threadname = "" ):

        #threading.Thread.__init__( self, name = threadname )

        super( myThread, self ).__init__( name = threadname )

    def run( self ):

        print "starting====", self.name, time.ctime()

        time.sleep( 5 )

        print "end====", self.name, time.ctime(),

 

m = myThread( "m" )

n = myThread( "n" )

 

m.start()

n.start()

输出的结果:

starting==== m Mon Aug 08 21:55:41 2011

starting==== n Mon Aug 08 21:55:41 2011

如果一个进程的主线程运行完毕而子线程还在执行的话,那么进程就不会退出,直到所有子线程结束为止。比如下面的例子:

import threading, time

class myThread( threading.Thread ):

    def __init__( self, threadname = "" ):

        #threading.Thread.__init__( self, name = threadname )

        super( myThread, self ).__init__( name = threadname )

    def run( self ):

        print "starting====", self.name, time.ctime()

        time.sleep( 5 )

        print "end====", self.name, time.ctime(),

 

m = myThread( "m" )

m.start()

print "main end"

print

输出的结果为:

starting==== m Mon Aug 08 22:01:06 2011

main end

end==== m Mon Aug 08 22:01:11 2011

也就是主进程结束之后,子进程还没有结束

如果我们想在主进程结束的时候,子进程也结束的话,我们就应该使用setDaemon()函数。

实例如下:

import threading, time

class myThread( threading.Thread ):

    def __init__( self, threadname = "" ):

        #threading.Thread.__init__( self, name = threadname )

        super( myThread, self ).__init__( name = threadname )

    def run( self ):

        print "starting====", self.name, time.ctime()

        time.sleep( 5 )

        print "end====", self.name, time.ctime(),

 

m = myThread( "m" )

m.setDaemon( True )

m.start()

print "main end"

print

输出的结果为:starting====main end m Mon Aug 08 22:02:58 2011

可以看出,并没有打印出子进程m结束的时候本应该打印的“end===…”

简单的线程同步

个执行线程经常要共享数据,如果仅仅读取共享数据还好,但是如果多个线程要修改共享数据的话就可能出现无法预料的结果。

假如两个线程对象t1和t2都要对数值num=0进行增1运算,那么t1和t2都各对num修改10次的话,那么num最终的结果应该为20。但是如果当t1取得num的值时(假如此时num为0),系统把t1调度为“sleeping”状态,而此时t2转换为“running”状态,此时t2获得的num的值也为0,然后他把num+1的值1赋给num。系统又把t2转化为“sleeping”状态,t1为“running”状态,由于t1已经得到num值为0,所以他也把num+1的值赋给了num为1。本来是2次增1运行,结果却是num只增了1次。类似这样的情况在多线程同时执行的时候是有可能发生的。所以为了防止这类情况的出现就要使用线程同步机制。

最简单的同步机制就是“锁”

锁对象用threading.RLock类创建

mylock = threading.RLock()

如何使用锁来同步线程呢?线程可以使用锁的acquire() (获得)方法,这样锁就进入“locked”状态。每次只有一个线程可以获得锁。如果当另一个线程试图获得这个锁的时候,就会被系统变为“blocked”状态,直到那个拥有锁的线程调用锁的release() (释放)方法,这样锁就会进入“unlocked”状态。“blocked”状态的线程就会收到一个通知,并有权利获得锁。如果多个线程处于“blocked”状态,所有线程都会先解除“blocked”状态,然后系统选择一个线程来获得锁,其他的线程继续沉默(“blocked”)。

import threading

mylock = threading.RLock()

class mythread(threading.Thread)

    ...

    def run(self ...):

        ...     #此处 不可以 放置修改共享数据的代码

        mylock.acquire()

        ...     #此处 可以 放置修改共享数据的代码

        mylock.release()

        ...     #此处 不可以 放置修改共享数据的代码

我们把修改共享数据的代码称为“临界区”,必须将所有“临界区”都封闭在同一锁对象的acquire()和release()方法调用之间。

锁只能提供最基本的同步级别。有时需要更复杂的线程同步,例如只在发生某些事件时才访问一个临界区(例如当某个数值改变时)。这就要使用“条件变量”。

条件变量用threading.Condition类创建

mycondition = threading.Condition()

条件变量是如何工作的呢?首先一个线程成功获得一个条件变量后,调用此条件变量的wait()方法会导致这个线程释放这个锁,并进入“blocked”状态,直到另一个线程调用同一个条件变量的notify()方法来唤醒那个进入“blocked”状态的线程。如果调用这个条件变量的notifyAll()方法的话就会唤醒所有的在等待的线程。

如果程序或者线程永远处于“blocked”状态的话,就会发生死锁。所以如果使用了锁、条件变量等同步机制的话,一定要注意仔细检查,防止死锁情况的发生。对于可能产生异常的临界区要使用异常处理机制中的finally子句来保证释放锁。等待一个条件变量的线程必须用notify()方法显式的唤醒,否则就永远沉默。保证每一个wait()方法调用都有一个相对应的notify()调用,当然也可以调用notifyAll()方法以防万一。

同步队列

我们经常会采用生产者/消费者关系的两个线程来处理一个共享缓冲区的数据。例如一个生产者线程接受用户数据放入一个共享缓冲区里,等待一个消费者线程对数据取出处理。但是如果缓冲区的太小而生产者和消费者两个异步线程的速度不同时,容易出现一个线程等待另一个情况。为了尽可能的缩短共享资源并以相同速度工作的各线程的等待时间,我们可以使用一个“队列”来提供额外的缓冲区。

创建一个“队列”对象,可以使用如下代码:

import Queue

myqueue = Queue.Queue(maxsize = 10)

Queue.Queue类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。

将一个值放入队列中:

myqueue.put(10)

调用队列对象的put()方法在队尾插入一个项目。put()有两个参数,第一个item为必需的,为插入项目的值;第二个block为可选参数,默认为1。如果队列当前为空且block为1,put()方法就使调用线程暂停,直到空出一个数据单元。如果block为0,put方法将引发Full异常。

将一个值从队列中取出:

myqueue.get()

调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为1。如果队列为空且block为1,get()就使调用线程暂停,直至有项目可用。如果block为0,队列将引发Empty异常。

我们用一个例子来展示如何使用Queue:

# queue_example.py

from Queue import Queue

import threading

import random

import time

 

# Producer thread

class Producer( threading.Thread ):

    def __init__( self, threadname, queue ):

        threading.Thread.__init__( self, name = threadname )

        self.sharedata = queue

    def run( self ):

        for i in range( 20 ):

            print self.getName(), 'adding', i, 'to queue'

            self.sharedata.put( i )

            time.sleep( random.randrange( 10 ) / 10.0 )

            print self.getName(), 'Finished'

 

# Consumer thread

class Consumer( threading.Thread ):

    def __init__( self, threadname, queue ):

        threading.Thread.__init__( self, name = threadname )

        self.sharedata = queue

    def run( self ):

        for i in range( 20 ):

            print self.getName(), 'got a value:', self.sharedata.get()

            time.sleep( random.randrange( 10 ) / 10.0 )

            print self.getName(), 'Finished'

 

# Main thread

def main():

    queue = Queue()

    producer = Producer( 'Producer', queue )

    consumer = Consumer( 'Consumer', queue )

 

    print 'Starting threads ...'

    producer.start()

    consumer.start()

 

    producer.join()

    consumer.join()

 

    print 'All threads have terminated.'

 

if __name__ == '__main__':

    main()

程序输出的结果为:

Starting threads ...

Producer adding 0 to queue

Consumer got a value: 0

Producer Finished

Producer adding 1 to queue

Producer Finished

Producer adding 2 to queue

Consumer Finished

Consumer got a value: 1

Consumer Finished

Consumer got a value: 2

Consumer Finished

Consumer got a value: Producer Finished

Producer adding 3 to queue

3

Consumer Finished

Consumer got a value: Producer Finished

Producer adding 4 to queue

4

ConsumerProducer Finished

 ConsumerFinished

got a value:Producer adding 5 to queue

5

Consumer Finished

Consumer got a value: Producer Finished

Producer adding 6 to queue

Producer Finished

Producer adding 7 to queue

6

Consumer Finished

Consumer got a value: 7

Producer Finished

Producer adding 8 to queue

Producer Finished

Producer adding 9 to queue

Consumer Finished

Consumer got a value: 8

ConsumerProducer  FinishedFinished

 

ConsumerProducer  got a value:adding 109

to queue

Producer Finished

Producer adding 11 to queue

Producer Finished

Producer adding 12 to queue

ConsumerProducer  FinishedFinished

 

ConsumerProducer  got a value:adding 1310

to queue

Producer Finished

Producer adding 14 to queue

Consumer Finished

Consumer got a value: 11

Producer Finished

Producer adding 15 to queue

Producer Finished

Producer adding 16 to queue

Producer Finished

Producer adding 17 to queue

Producer Finished

Producer adding 18 to queue

Consumer Finished

Consumer got a value: 12

Producer Finished

Producer adding 19 to queue

Producer Finished

Consumer Finished

Consumer got a value: 13

Consumer Finished

Consumer got a value: 14

Consumer Finished

Consumer got a value: 15

Consumer Finished

Consumer got a value: 16

Consumer Finished

Consumer got a value: 17

Consumer Finished

Consumer got a value: 18

Consumer Finished

Consumer got a value: 19

Consumer Finished

All threads have terminated.

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
Python中__new__与__init__方法的区别详解
May 04 Python
python+Django+apache的配置方法详解
Jun 01 Python
Python 序列的方法总结
Oct 18 Python
浅谈python中的正则表达式(re模块)
Oct 17 Python
Python中字典的浅拷贝与深拷贝用法实例分析
Jan 02 Python
python 2.7.13 安装配置方法图文教程
Sep 18 Python
Python 支付整合开发包的实现
Jan 23 Python
python判断文件是否存在,不存在就创建一个的实例
Feb 18 Python
Python3.7 dataclass使用指南小结
Feb 22 Python
python安装numpy和pandas的方法步骤
May 27 Python
django中瀑布流写法实例代码
Oct 14 Python
python实现单目标、多目标、多尺度、自定义特征的KCF跟踪算法(实例代码)
Jan 08 Python
Python中os.path用法分析
Jan 15 #Python
python静态方法实例
Jan 14 #Python
python继承和抽象类的实现方法
Jan 14 #Python
python列表操作实例
Jan 14 #Python
python操作gmail实例
Jan 14 #Python
Python中的装饰器用法详解
Jan 14 #Python
python登陆asp网站页面的实现代码
Jan 14 #Python
You might like
java EJB 加密与解密原理的一个例子
2008/01/11 PHP
php 生成随机验证码图片代码
2010/02/08 PHP
PHP守护进程化在C和PHP环境下的实现
2017/11/21 PHP
PHP实现将多个文件压缩成zip格式并下载到本地的方法示例
2018/05/23 PHP
javascript实现 在光标处插入指定内容
2007/05/25 Javascript
jQuery弹出层插件简化版代码下载
2008/10/16 Javascript
Jquery乱码的一次解决过程 图解教程
2010/02/20 Javascript
理解Javascript_02_理解undefined和null
2010/10/11 Javascript
jquery批量设置属性readonly和disabled的方法
2014/01/24 Javascript
jQuery简易图片放大特效示例代码
2014/06/09 Javascript
JavaScript中的方法调用详细介绍
2014/12/30 Javascript
解决ueditor jquery javascript 取值问题
2014/12/30 Javascript
嵌入式iframe子页面与父页面js通信的方法
2015/01/20 Javascript
jquery制作 随机弹跳的小球特效
2015/02/01 Javascript
jQuery实现大转盘抽奖活动仿QQ音乐代码分享
2015/08/21 Javascript
JQuery动态添加Select的Option元素实现方法
2016/08/29 Javascript
JavaScript中boolean类型之三种情景实例代码
2016/11/21 Javascript
Sequelize中用group by进行分组聚合查询
2016/12/12 Javascript
微信小程序 五星评分(包括半颗星评分)实例代码
2016/12/14 Javascript
在ABP框架中使用BootstrapTable组件的方法
2017/07/31 Javascript
微信小程序实现城市列表选择
2018/06/05 Javascript
JavaScript实现手机号码 3-4-4格式并控制新增和删除时光标的位置
2020/06/02 Javascript
Threejs实现滴滴官网首页地球动画功能
2020/07/13 Javascript
[02:07]DOTA2新英雄展现中国元素,完美“圣典”亮相央视
2016/12/19 DOTA
python结合opencv实现人脸检测与跟踪
2015/06/08 Python
python实现支付宝当面付(扫码支付)功能
2018/05/30 Python
python3.6+selenium实现操作Frame中的页面元素
2019/07/16 Python
python中几种自动微分库解析
2019/08/29 Python
pygame实现俄罗斯方块游戏(对战篇1)
2019/10/29 Python
2020年10款优秀的Python第三方库,看看有你中意的吗?
2021/01/12 Python
丹尼尔惠灵顿手表天猫官方旗舰店:Daniel Wellington
2017/08/25 全球购物
沙龙级头发造型工具:FOXYBAE
2018/07/01 全球购物
Lookfantastic俄罗斯:欧洲在线化妆品零售商
2019/08/06 全球购物
销售简历自我评价
2014/01/24 职场文书
2015年学校减负工作总结
2015/05/19 职场文书
Python编写可视化界面的全过程(Python+PyCharm+PyQt)
2021/05/17 Python