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中处理字符串之islower()方法的使用简介
May 19 Python
利用Python查看目录中的文件示例详解
Aug 28 Python
简单实现python聊天程序
Apr 01 Python
Python Logging 日志记录入门学习
Jun 02 Python
python tornado微信开发入门代码
Aug 24 Python
对Python 语音识别框架详解
Dec 24 Python
Python的互斥锁与信号量详解
Sep 12 Python
python读写Excel表格的实例代码(简单实用)
Dec 19 Python
python批量修改xml属性的实现方式
Mar 05 Python
Python+Xlwings 删除Excel的行和列
Dec 19 Python
Pycharm创建python文件自动添加日期作者等信息(步骤详解)
Feb 03 Python
python实现杨辉三角的几种方法代码实例
Mar 02 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
通过html表格发电子邮件
2006/10/09 PHP
解析php中的fopen()函数用打开文件模式说明
2013/06/20 PHP
php strnatcmp()函数的用法总结
2013/11/27 PHP
全面解读PHP的Yii框架中的日志功能
2016/03/17 PHP
laravel框架语言包拓展实现方法分析
2019/11/22 PHP
Javascript 定时器调用传递参数的方法
2009/11/12 Javascript
整理8个很棒的 jQuery 倒计时插件和教程
2011/12/12 Javascript
jquery 3D 标签云示例代码
2014/06/12 Javascript
js+cookies实现悬浮购物车的方法
2015/05/25 Javascript
javascript原型模式用法实例详解
2015/06/04 Javascript
php利用curl获取远程图片实现方法
2015/10/26 Javascript
详解Webwork中Action 调用的方法
2016/02/02 Javascript
node.js插件nodeclipse安装图文教程
2020/10/19 Javascript
jQuery实现表格文本框淡入更改值后淡出效果
2016/09/27 Javascript
JS正则RegExp.test()使用注意事项(不具有重复性)
2016/12/28 Javascript
react-router实现跳转传值的方法示例
2017/05/27 Javascript
一步步教你利用Docker设置Node.js
2018/11/20 Javascript
js实现图片局部放大效果详解
2019/03/18 Javascript
微信小程序实现的图片保存功能示例
2019/04/24 Javascript
webpack4之如何编写loader的方法步骤
2019/06/06 Javascript
p5.js绘制旋转的正方形
2019/10/23 Javascript
JavaScript实现手风琴效果
2021/02/18 Javascript
Python判断文本中消息重复次数的方法
2016/04/27 Python
Python使用内置json模块解析json格式数据的方法
2017/07/20 Python
Python使用python-docx读写word文档
2019/08/26 Python
python绘制动态曲线教程
2020/02/24 Python
浅谈PyTorch中in-place operation的含义
2020/06/27 Python
日本高岛屋百货购物网站:TAKASHIMAYA
2019/03/24 全球购物
英国曼彻斯特宠物用品品牌:Bunty Pet Products
2019/07/27 全球购物
主键(Primary Key)约束和唯一性(UNIQUE)约束的区别
2013/05/29 面试题
后勤主管岗位职责
2014/03/01 职场文书
教师党员承诺书
2014/03/25 职场文书
经费申请报告范文
2015/05/18 职场文书
如何起草一份正确的合伙创业协议书?
2019/07/04 职场文书
python实现过滤敏感词
2021/05/08 Python
带你学习MySQL执行计划
2021/05/31 MySQL