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实现simhash算法实例
Apr 25 Python
python脚本实现分析dns日志并对受访域名排行
Sep 18 Python
python实现傅里叶级数展开的实现
Jul 21 Python
解决python中画图时x,y轴名称出现中文乱码的问题
Jan 29 Python
Python动态语言与鸭子类型详解
Jul 01 Python
python django model联合主键的例子
Aug 06 Python
python单向链表的基本实现与使用方法【定义、遍历、添加、删除、查找等】
Oct 24 Python
基于python判断目录或者文件代码实例
Nov 29 Python
解决Tensorflow占用GPU显存问题
Feb 03 Python
如何在python开发工具PyCharm中搭建QtPy环境(教程详解)
Feb 04 Python
Python greenlet和gevent使用代码示例解析
Apr 01 Python
python 实现的IP 存活扫描脚本
Dec 10 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
ecshop 批量上传(加入自定义属性)
2012/03/20 PHP
如何用PHP实现插入排序?
2013/04/10 PHP
PHP设计模式之责任链模式的深入解析
2013/06/13 PHP
php组合排序简单实现方法
2016/10/15 PHP
PJ Blog修改-禁止复制的代码和方法
2006/10/25 Javascript
jquery手风琴特效插件
2015/02/04 Javascript
JavaScript在浏览器标题栏上显示当前日期和时间的方法
2015/03/19 Javascript
简单谈谈node.js 版本控制 nvm和 n
2015/10/15 Javascript
总结在前端排序中遇到的问题
2016/07/19 Javascript
jQuery基本选择器之标签名选择器
2016/09/03 Javascript
jquery.multiselect多选下拉框实现代码
2016/11/11 Javascript
Node.js复制文件的方法示例
2016/12/29 Javascript
Vue数据驱动模拟实现2
2017/01/11 Javascript
JS库之wow.js使用方法
2017/09/14 Javascript
angularjs实现猜大小功能
2017/10/23 Javascript
AngularJS使用ng-repeat遍历二维数组元素的方法详解
2017/11/11 Javascript
基于 Vue.js 之 iView UI 框架非工程化实践记录(推荐)
2017/11/21 Javascript
Vue项目添加动态浏览器头部title的方法
2018/07/11 Javascript
浅谈webpack SplitChunksPlugin实用指南
2018/09/17 Javascript
vuex 动态注册方法 registerModule的实现
2019/07/03 Javascript
layui监听单元格编辑前后交互的例子
2019/09/16 Javascript
keep-alive不能缓存多层级路由菜单问题解决
2020/03/10 Javascript
JS call()及apply()方法使用实例汇总
2020/07/11 Javascript
利用python GDAL库读写geotiff格式的遥感影像方法
2018/11/29 Python
Python中psutil的介绍与用法
2019/05/02 Python
[机器视觉]使用python自动识别验证码详解
2019/05/16 Python
CSS3 Flexbox中flex-shrink属性的用法示例介绍
2013/12/30 HTML / CSS
基于zepto的插件之移动端无缝向上滚动并上下触摸滑动实例代码
2016/12/20 HTML / CSS
JBL美国官方商店:扬声器、耳机等
2019/12/01 全球购物
GC是什么?为什么要有GC?
2013/12/08 面试题
函授毕业自我鉴定
2014/02/04 职场文书
2014年五四青年节活动方案
2014/03/29 职场文书
推广普通话标语
2014/06/27 职场文书
低碳环保演讲稿
2014/08/28 职场文书
初三英语教学反思
2016/02/15 职场文书
Java完整实现记事本代码
2022/06/16 Java/Android