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读写Excel文件的实例
Nov 01 Python
python列表与元组详解实例
Nov 01 Python
详解Swift中属性的声明与作用
Jun 30 Python
Python cookbook(数据结构与算法)让字典保持有序的方法
Feb 18 Python
python奇偶行分开存储实现代码
Mar 19 Python
python的concat等多种用法详解
Nov 28 Python
python代码 输入数字使其反向输出的方法
Dec 22 Python
Python 网络编程之TCP客户端/服务端功能示例【基于socket套接字】
Oct 12 Python
使用python动态生成波形曲线的实现
Dec 04 Python
Python基于类路径字符串获取静态属性
Mar 12 Python
Django Model层F,Q对象和聚合函数原理解析
Nov 12 Python
jupyter notebook保存文件默认路径更改方法汇总(亲测可以)
Jun 09 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
php使用PDO方法详解
2014/12/27 PHP
PHP实现指定字段的多维数组排序函数分享
2015/03/09 PHP
深入讲解PHP的Yii框架中的属性(Property)
2016/03/18 PHP
laravel 实现向公共模板中传值 (view composer)
2019/10/22 PHP
js获取变量
2006/08/24 Javascript
跟随鼠标旋转的文字
2006/11/30 Javascript
ExtJS 入门
2010/10/29 Javascript
js取消单选按钮选中并判断对象是否为空
2013/11/14 Javascript
两种方法基于jQuery实现IE浏览器兼容placeholder效果
2014/10/14 Javascript
Bootstarp风格的toggle效果分享
2016/02/23 Javascript
JS组件系列之Bootstrap table表格组件神器【终结篇】
2016/05/10 Javascript
javascript中BOM基础知识总结
2017/02/14 Javascript
深入理解AngularJs-scope的脏检查(一)
2017/06/19 Javascript
angular学习之从零搭建一个angular4.0项目
2017/07/10 Javascript
JavaScript获取用户所在城市及地理位置
2018/04/21 Javascript
详解js跨域请求的两种方式,支持post请求
2018/05/05 Javascript
关于jquery中attr()和prop()方法的区别
2018/05/28 jQuery
详解webpack2异步加载套路
2018/09/14 Javascript
node koa2 ssr项目搭建的方法步骤
2020/12/11 Javascript
[09:23]国际邀请赛采访专栏:iG战队VK,Tongfu战队Cu
2013/08/05 DOTA
python中pika模块问题的深入探究
2018/10/13 Python
python ipset管理 增删白名单的方法
2019/01/14 Python
Python基础知识点 初识Python.md
2019/05/14 Python
Python读取xlsx文件的实现方法
2019/07/04 Python
PowerBI和Python关于数据分析的对比
2019/07/11 Python
python pandas 时间日期的处理实现
2019/07/30 Python
Django ORM实现按天获取数据去重求和例子
2020/05/18 Python
Django contrib auth authenticate函数源码解析
2020/11/12 Python
Jupyter notebook命令和编辑模式常用快捷键汇总
2020/11/17 Python
eharmony澳大利亚:网上约会服务
2020/02/29 全球购物
法学专业个人求职信
2013/09/26 职场文书
专升本自我鉴定
2013/10/10 职场文书
个人找工作求职简历的自我评价
2013/10/20 职场文书
美发活动策划书
2014/01/14 职场文书
2015年社区流动人口工作总结
2015/05/12 职场文书
Vue3中toRef与toRefs的区别
2022/03/24 Vue.js