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实现代理服务功能实例
Nov 15 Python
Python中subprocess模块用法实例详解
May 20 Python
python中的break、continue、exit()、pass全面解析
Aug 05 Python
详解PyCharm配置Anaconda的艰难心路历程
Aug 13 Python
spark dataframe 将一列展开,把该列所有值都变成新列的方法
Jan 29 Python
pyqt5利用pyqtDesigner实现登录界面
Mar 28 Python
Python实现12306火车票抢票系统
Jul 04 Python
python实现智能语音天气预报
Dec 02 Python
pandas读取csv文件提示不存在的解决方法及原因分析
Apr 21 Python
python filecmp.dircmp实现递归比对两个目录的方法
May 22 Python
Python爬虫防封ip的一些技巧
Aug 06 Python
解决Python中的modf()函数取小数部分不准确问题
May 28 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
thinkphp普通查询与表达式查询实例分析
2014/11/24 PHP
Zend Framework使用Zend_Loader组件动态加载文件和类用法详解
2016/12/09 PHP
jQuery:delegate中select()不起作用的解决方法(实例讲解)
2014/01/26 Javascript
jQuery事件之键盘事件(ctrl+Enter回车键提交表单等)
2014/05/11 Javascript
JavaScript实现在标题栏上显示当前日期的方法
2015/03/19 Javascript
nodejs通过phantomjs实现下载网页
2015/05/04 NodeJs
javascript实现的图片切割多块效果实例
2015/05/07 Javascript
基于JavaScript的操作系统你听说过吗?
2016/01/28 Javascript
为什么JavaScript没有块级作用域
2016/05/22 Javascript
详解angular2封装material2对话框组件
2017/03/03 Javascript
axios学习教程全攻略
2017/03/26 Javascript
jqgrid实现简单的单行编辑功能
2017/09/30 Javascript
vue 子组件向父组件传值方法
2018/02/26 Javascript
vue父组件向子组件传递多个数据的实例
2018/03/01 Javascript
vue渲染时闪烁{{}}的问题及解决方法
2018/03/28 Javascript
JavaScript动态创建二维数组的方法示例
2019/02/01 Javascript
Vue自定义指令上报Google Analytics事件统计的方法
2019/02/25 Javascript
webpack3升级到webpack4遇到问题总结
2019/09/30 Javascript
jQuery实现html可联动的百分比进度条
2020/03/26 jQuery
[07:48]DOTA2上海特级锦标赛主赛事首日RECAP
2016/03/04 DOTA
python常见的格式化输出小结
2016/12/15 Python
pandas groupby 分组取每组的前几行记录方法
2018/04/20 Python
OpenCV里的imshow()和Matplotlib.pyplot的imshow()的实现
2019/11/25 Python
pycharm下配置pyqt5的教程(anaconda虚拟环境下+tensorflow)
2020/03/25 Python
CSS3实现银灰色动画效果的导航菜单代码
2015/09/01 HTML / CSS
CSS3 rgb and rgba(透明色)的使用详解
2020/09/25 HTML / CSS
html5 css3实例教程 一款html5和css3实现的小机器人走路动画
2014/10/20 HTML / CSS
浅谈基于Canvas的手绘风格图形库Rough.js
2018/03/19 HTML / CSS
html5移动端价格输入键盘的实现
2019/09/16 HTML / CSS
文明学生事迹材料
2014/01/29 职场文书
安全教育月活动总结
2014/05/05 职场文书
文明寝室标语
2014/06/13 职场文书
法院四风对照检查材料思想汇报
2014/10/06 职场文书
毕业实习证明范本
2015/06/16 职场文书
贫困证明怎么写
2015/06/16 职场文书
python引入其他文件夹下的py文件具体方法
2021/05/23 Python