设为首页 收藏本站
查看: 683|回复: 0

[经验分享] python 多线程编程

[复制链接]

尚未签到

发表于 2015-4-24 09:59:17 | 显示全部楼层 |阅读模式
  一)线程基础
  1、创建线程:
  thread模块提供了start_new_thread函数,用以创建线程。start_new_thread函数成功创建后还能够对其进行操作。
  其函数原型:
  start_new_thread(function,atgs[,kwargs])
  其參数含义例如以下:
  function: 在线程中运行的函数名
  args:元组形式的參数列表。
  kwargs: 可选參数,以字典的形式指定參数
  方法一:通过使用thread模块中的函数创建新线程。
  >>> import thread>>> def run(n):for i in range(n):print i>>> thread.start_new_thread(run,(4,))   #注意第二个參数一定要是元组的形式538401>>> 23KeyboardInterrupt>>> thread.start_new_thread(run,(2,))178401>>> thread.start_new_thread(run,(),{'n':4})397201>>> 23thread.start_new_thread(run,(),{'n':3})324801>>> 2
  方法二:通过继承threading.Thread创建线程
  >>> import threading>>> class mythread(threading.Thread):def __init__(self,num):threading.Thread.__init__(self)self.num = numdef run(self):               #重载run方法print 'I am', self.num>>> t1 = mythread(1)>>> t2 = mythread(2)>>> t3 = mythread(3)>>> t1.start()           #执行线程t1I am>>>  1t2.start()I am>>>  2t3.start()I am>>>  3
  方法三:使用threading.Thread直接在线程中执行函数。
  import threading>>> def run(x,y):for i in range(x,y):print i>>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函数args为函数參数>>> t1.start()15>>> 16171819
  
  二)Thread对象中的经常用法:
  1、isAlive方法:
  >>> import threading>>> import time>>> class mythread(threading.Thread):def __init__(self,id):threading.Thread.__init__(self)self.id = iddef run(self):time.sleep(5)    #休眠5秒print self.id>>> t = mythread(1)>>> def func():t.start()print t.isAlive()    #打印线程状态>>> func()True>>> 1
  2、join方法:
  原型:join([timeout])
  timeout: 可选參数,线程执行的最长时间
  import threading>>> import time     #导入time模块>>> class Mythread(threading.Thread):def __init__(self,id):threading.Thread.__init__(self)self.id = iddef run(self):x = 0time.sleep(20)print self.id>>> def func():t.start()for i in range(5):print i>>> t = Mythread(2)>>> func()01234>>> 2def func():t.start()t.join()for i in range(5):print i>>> t = Mythread(3)>>> func()301234>>>  
  
  3、线程名:
  >>> import threading>>> class mythread(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name=threadname)def run(self):print self.getName()>>> >>> t1 = mythread('t1')>>> t1.start()t1>>>  
  4、setDaemon方法
  在脚本执行的过程中有一个主线程,假设主线程又创建了一个子线程,那么当主线程退出时,会检验子线程是否完毕。假设子线程未完毕,则主线程会在等待子线程完毕后退出。
  当须要主线程退出时,无论子线程是否完毕都随主线程退出,则能够使用Thread对象的setDaemon方法来设置。
  
  三)线程同步
  1.简单的线程同步
  使用Thread对象的Lock和RLock能够实现简单的线程同步。对于假设须要每次仅仅有一个线程操作的数据,能够将操作过程放在acquire方法和release方法之间。如:
  # -*- coding:utf-8 -*-import threadingimport timeclass mythread(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name = threadname)def run(self):global x                #设置全局变量#lock.acquire()          #调用lock的acquire方法for i in range(3):x = x + 1time.sleep(2)print x#lock.release()          #调用lock的release方法#lock = threading.RLock()        #生成Rlock对象t1 = []for i in range(10):t = mythread(str(i))t1.append(t)x = 0                   #将全局变量的值设为0for i in t1: i.start()E:/study/python/workspace>xianchengtongbu.py36912151821242730
  假设将lock.acquire()和lock.release(),lock = threading.Lock()删除后保存执行脚本,结果将是输出10个30。30是x的终于值,因为x是全局变量,每一个线程对其操作后进入休眠状态,在线程休眠的时候,python解释器就执行了其它的线程而是x的值添加。当全部线程休眠结束后,x的值已被全部线改动为了30,因此输出全部为30。
  
  2、使用条件变量保持线程同步。
  Python的Condition对象提供了对复制线程同步的支持。使用Condition对象能够在某些事件触发后才处理数据。Condition对象除了具有acquire方法和release的方法外,还有wait方法、notify方法、notifyAll方法等用于条件处理。
  # -*- coding:utf-8 -*-import threadingclass Producer(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name = threadname)def run(self):global xcon.acquire()if x == 1000000:con.wait()#passelse:for i in range(1000000):x = x + 1con.notify()print xcon.release()class Consumer(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name = threadname)def run(self):global x con.acquire()if x == 0:con.wait()#passelse:for i in range(1000000):x = x - 1con.notify()print x con.release()con = threading.Condition()x = 0p = Producer('Producer')c = Consumer('Consumer')p.start()c.start()p.join()c.join()print xE:/study/python/workspace>xianchengtongbu2.py100000000
  线程间通信:
  Event对象用于线程间的相互通信。他提供了设置信号、清除信宏、等待等用于实现线程间的通信。
  1、设置信号。Event对象使用了set()方法后,isSet()方法返回真。
  2、清除信号。使用Event对象的clear()方法后,isSet()方法返回为假。
  3、等待。当Event对象的内部信号标志为假时,则wait()方法一直等到其为真时才返回。还能够向wait传递參数,设定最长的等待时间。
  # -*- coding:utf-8 -*-import threadingclass mythread(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name = threadname)def run(self):global eventif event.isSet():event.clear()event.wait()   #当event被标记时才返回print self.getName()else:print self.getName()event.set()event = threading.Event()event.set()t1 = []for i in range(10):t = mythread(str(i))t1.append(t)for i in t1:i.start()

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-60204-1-1.html 上篇帖子: python中的深浅拷贝 下篇帖子: Python和Decorator(装饰器)模式
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表