国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 多線程的實例詳解

2020-01-04 16:41:49
字體:
來源:轉載
供稿:網友

 Python 多線程的實例詳解

一)線程基礎

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,))  #注意第二個參數一定要是元組的形式 53840   1 >>>  2 3 KeyboardInterrupt >>> thread.start_new_thread(run,(2,)) 17840   1 >>>  thread.start_new_thread(run,(),{'n':4}) 39720   1 >>>  2 3 thread.start_new_thread(run,(),{'n':3}) 32480   1 >>>  2 

方法二:通過繼承threading.Thread創建線程

>>> import threading >>> class mythread(threading.Thread):   def __init__(self,num):     threading.Thread.__init__(self)     self.num = num   def run(self):        #重載run方法     print 'I am', self.num       >>> t1 = mythread(1) >>> t2 = mythread(2) >>> t3 = mythread(3) >>> t1.start()      #運行線程t1 I am >>> 1 t2.start() I am >>> 2 t3.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 >>>  16 17 18 19 

二)Thread對象中的常用方法:

1、isAlive方法:

>>> import threading >>> import time >>> class mythread(threading.Thread):   def __init__(self,id):     threading.Thread.__init__(self)     self.id = id   def 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 = id   def run(self):     x = 0     time.sleep(20)     print self.id       >>> def func():   t.start()   for i in range(5):     print i       >>> t = Mythread(2) >>> func() 0 1 2 3 4 >>> 2 def func():   t.start()   t.join()   for i in range(5):     print i       >>> t = Mythread(3) >>> func() 3 0 1 2 3 4 >>>  

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 threading import time class 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 + 1     time.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          #將全局變量的值設為0 for i in t1:    i.start()  E:/study/<a href="http://lib.csdn.net/base/python" rel="external nofollow" class='replace_word'  def __init__(self,threadname):     threading.Thread.__init__(self,name = threadname)   def run(self):     global x     con.acquire()     if x == 1000000:       con.wait()     #  pass     else:       for i in range(1000000):         x = x + 1       con.notify()     print x     con.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()       #pass     else:       for i in range(1000000):         x = x - 1       con.notify()     print x      con.release() con = threading.Condition() x = 0 p = Producer('Producer') c = Consumer('Consumer') p.start() c.start() p.join() c.join() print x  E:/study/python/workspace>xianchengtongbu2.py 1000000 0 0 

線程間通信:

Event對象用于線程間的相互通信。他提供了設置信號、清除信宏、等待等用于實現線程間的通信。

1、設置信號。Event對象使用了set()方法后,isSet()方法返回真。
2、清除信號。使用Event對象的clear()方法后,isSet()方法返回為假。
3、等待。當Event對象的內部信號標志為假時,則wait()方法一直等到其為真時才返回。還可以向wait傳遞參數,設定最長的等待時間。

# -*- coding:utf-8 -*- import threading class mythread(threading.Thread):   def __init__(self,threadname):     threading.Thread.__init__(self,name = threadname)   def run(self):     global event     if 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() 

如有疑問請留言或者到本站社區交流討論,感謝 閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 双流县| 东丽区| 塘沽区| 清河县| 虞城县| 嫩江县| 界首市| 崇明县| 怀宁县| 舞钢市| 安福县| 华坪县| 大港区| 龙川县| 来安县| 陕西省| 沙洋县| 武邑县| 荔波县| 吉安县| 云南省| 肃北| 汪清县| 丰县| 泸西县| 屯门区| 建瓯市| 宝兴县| 微博| 江都市| 勃利县| 奉贤区| 句容市| 台州市| 沭阳县| 通化县| 三明市| 道真| 弥勒县| 临海市| 思茅市|