乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      python 多線程編程

       小豬窩969 2015-04-10

      一)線程基礎(chǔ)

      1、創(chuàng)建線程:

      thread模塊提供了start_new_thread函數(shù),用以創(chuàng)建線程。start_new_thread函數(shù)成功創(chuàng)建后還可以對(duì)其進(jìn)行操作。

      其函數(shù)原型:

          start_new_thread(function,atgs[,kwargs])

      其參數(shù)含義如下:

          function: 在線程中執(zhí)行的函數(shù)名

          args:元組形式的參數(shù)列表。

          kwargs: 可選參數(shù),以字典的形式指定參數(shù)

      方法一:通過使用thread模塊中的函數(shù)創(chuàng)建新線程。

      1. >>> import thread  
      2. >>> def run(n):  
      3.     for i in range(n):  
      4.         print i  
      5.   
      6.           
      7. >>> thread.start_new_thread(run,(4,))   #注意第二個(gè)參數(shù)一定要是元組的形式  
      8. 53840  
      9.   
      10.   
      11. 1  
      12. >>>   
      13. 2  
      14. 3  
      15. KeyboardInterrupt  
      16. >>> thread.start_new_thread(run,(2,))  
      17. 17840  
      18.   
      19.   
      20. 1  
      21. >>>   
      22. thread.start_new_thread(run,(),{'n':4})  
      23. 39720  
      24.   
      25.   
      26. 1  
      27. >>>   
      28. 2  
      29. 3  
      30. thread.start_new_thread(run,(),{'n':3})  
      31. 32480  
      32.   
      33.   
      34. 1  
      35. >>>   
      36. 2  

      方法二:通過繼承threading.Thread創(chuàng)建線程

      1. >>> import threading  
      2. >>> class mythread(threading.Thread):  
      3.     def __init__(self,num):  
      4.         threading.Thread.__init__(self)  
      5.         self.num = num  
      6.     def run(self):               #重載run方法  
      7.         print 'I am', self.num  
      8.   
      9.           
      10. >>> t1 = mythread(1)  
      11. >>> t2 = mythread(2)  
      12. >>> t3 = mythread(3)  
      13. >>> t1.start()           #運(yùn)行線程t1  
      14. I am  
      15. >>>  1  
      16. t2.start()  
      17. I am  
      18. >>>  2  
      19. t3.start()  
      20. I am  
      21. >>>  3  

      方法三:使用threading.Thread直接在線程中運(yùn)行函數(shù)。

      1. import threading  
      2. >>> def run(x,y):  
      3.     for i in range(x,y):  
      4.         print i  
      5.   
      6. >>> t1 = threading.Thread(target=run,args=(15,20)) #直接使用Thread附加函數(shù)args為函數(shù)參數(shù)  
      7.   
      8. >>> t1.start()  
      9. 15  
      10. >>>   
      11. 16  
      12. 17  
      13. 18  
      14. 19  

       

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

      1、isAlive方法:

      1. >>> import threading  
      2. >>> import time  
      3. >>> class mythread(threading.Thread):  
      4.     def __init__(self,id):  
      5.         threading.Thread.__init__(self)  
      6.         self.id = id  
      7.     def run(self):  
      8.         time.sleep(5)    #休眠5秒  
      9.         print self.id  
      10.   
      11.           
      12. >>> t = mythread(1)  
      13. >>> def func():  
      14.     t.start()  
      15.     print t.isAlive()    #打印線程狀態(tài)  
      16.   
      17.       
      18. >>> func()  
      19. True  
      20. >>> 1  

      2、join方法:

      原型:join([timeout]) 

          timeout: 可選參數(shù),線程運(yùn)行的最長時(shí)間

      1. import threading  
      2. >>> import time     #導(dǎo)入time模塊  
      3. >>> class Mythread(threading.Thread):  
      4.     def __init__(self,id):  
      5.         threading.Thread.__init__(self)  
      6.         self.id = id  
      7.     def run(self):  
      8.         x = 0  
      9.         time.sleep(20)  
      10.         print self.id  
      11.   
      12.           
      13. >>> def func():  
      14.     t.start()  
      15.     for i in range(5):  
      16.         print i  
      17.   
      18.           
      19. >>> t = Mythread(2)  
      20. >>> func()  
      21. 0  
      22. 1  
      23. 2  
      24. 3  
      25. 4  
      26. >>> 2  
      27. def func():  
      28.     t.start()  
      29.     t.join()  
      30.     for i in range(5):  
      31.         print i  
      32.   
      33.           
      34. >>> t = Mythread(3)  
      35. >>> func()  
      36. 3  
      37. 0  
      38. 1  
      39. 2  
      40. 3  
      41. 4  
      42. >>>   

       

      3、線程名:

      1. >>> import threading  
      2. >>> class mythread(threading.Thread):  
      3.     def __init__(self,threadname):  
      4.         threading.Thread.__init__(self,name=threadname)  
      5.     def run(self):  
      6.         print self.getName()  
      7.   
      8.           
      9. >>>   
      10. >>> t1 = mythread('t1')  
      11. >>> t1.start()  
      12. t1  
      13. >>>   

       4、setDaemon方法

      在腳本運(yùn)行的過程中有一個(gè)主線程,如果主線程又創(chuàng)建了一個(gè)子線程,那么當(dāng)主線程退出時(shí),會(huì)檢驗(yàn)子線程是否完成。如果子線程未完成,則主線程會(huì)在等待子線程完成后退出。

      當(dāng)需要主線程退出時(shí),不管子線程是否完成都隨主線程退出,則可以使用Thread對(duì)象的setDaemon方法來設(shè)置。

       

      三)線程同步

      1.簡單的線程同步

      使用Thread對(duì)象的Lock和RLock可以實(shí)現(xiàn)簡單的線程同步。對(duì)于如果需要每次只有一個(gè)線程操作的數(shù)據(jù),可以將操作過程放在acquire方法和release方法之間。如:

       

      1. # -*- coding:utf-8 -*-  
      2. import threading  
      3. import time  
      4. class mythread(threading.Thread):  
      5.     def __init__(self,threadname):  
      6.         threading.Thread.__init__(self,name = threadname)  
      7.     def run(self):  
      8.         global x                #設(shè)置全局變量  
      9. #       lock.acquire()          #調(diào)用lock的acquire方法  
      10.         for i in range(3):  
      11.             x = x + 1  
      12.         time.sleep(2)  
      13.         print x  
      14. #       lock.release()          #調(diào)用lock的release方法  
      15. #lock = threading.RLock()        #生成Rlock對(duì)象  
      16. t1 = []  
      17. for i in range(10):  
      18.     t = mythread(str(i))  
      19.     t1.append(t)  
      20. x = 0                   #將全局變量的值設(shè)為0  
      21. for i in t1:   
      22.     i.start()  
      23.   
      24. E:/study/python/workspace>xianchengtongbu.py  
      25. 3  
      26. 6  
      27. 9  
      28. 12  
      29. 15  
      30. 18  
      31. 21  
      32. 24  
      33. 27  
      34. 30  

      如果將lock.acquire()和lock.release(),lock = threading.Lock()刪除后保存運(yùn)行腳本,結(jié)果將是輸出10個(gè)30。30是x的最終值,由于x是全局變量,每個(gè)線程對(duì)其操作后進(jìn)入休眠狀態(tài),在線程休眠的時(shí)候,python解釋器就執(zhí)行了其他的線程而是x的值增加。當(dāng)所有線程休眠結(jié)束后,x的值已被所有線修改為了30,因此輸出全部為30。

       

      2、使用條件變量保持線程同步。

      Python的Condition對(duì)象提供了對(duì)復(fù)制線程同步的支持。使用Condition對(duì)象可以在某些事件觸發(fā)后才處理數(shù)據(jù)。Condition對(duì)象除了具有acquire方法和release的方法外,還有wait方法、notify方法、notifyAll方法等用于條件處理。

      1. # -*- coding:utf-8 -*-  
      2. import threading  
      3. class Producer(threading.Thread):  
      4.     def __init__(self,threadname):  
      5.         threading.Thread.__init__(self,name = threadname)  
      6.     def run(self):  
      7.         global x  
      8.         con.acquire()  
      9.         if x == 1000000:  
      10.             con.wait()  
      11.         #   pass  
      12.         else:  
      13.             for i in range(1000000):  
      14.                 x = x + 1  
      15.             con.notify()  
      16.         print x  
      17.         con.release()  
      18. class Consumer(threading.Thread):  
      19.     def __init__(self,threadname):  
      20.         threading.Thread.__init__(self,name = threadname)  
      21.     def run(self):  
      22.         global x   
      23.         con.acquire()  
      24.         if x == 0:  
      25.             con.wait()  
      26.             #pass  
      27.         else:  
      28.             for i in range(1000000):  
      29.                 x = x - 1  
      30.             con.notify()  
      31.         print x   
      32.         con.release()  
      33. con = threading.Condition()  
      34. x = 0  
      35. p = Producer('Producer')  
      36. c = Consumer('Consumer')  
      37. p.start()  
      38. c.start()  
      39. p.join()  
      40. c.join()  
      41. print x  
      42.   
      43. E:/study/python/workspace>xianchengtongbu2.py  
      44. 1000000  
      45. 0  
      46. 0  

      線程間通信:

      Event對(duì)象用于線程間的相互通信。他提供了設(shè)置信號(hào)、清除信宏、等待等用于實(shí)現(xiàn)線程間的通信。

      1、設(shè)置信號(hào)。Event對(duì)象使用了set()方法后,isSet()方法返回真。

      2、清除信號(hào)。使用Event對(duì)象的clear()方法后,isSet()方法返回為假。

      3、等待。當(dāng)Event對(duì)象的內(nèi)部信號(hào)標(biāo)志為假時(shí),則wait()方法一直等到其為真時(shí)才返回。還可以向wait傳遞參數(shù),設(shè)定最長的等待時(shí)間。

      1. # -*- coding:utf-8 -*-  
      2. import threading  
      3. class mythread(threading.Thread):  
      4.     def __init__(self,threadname):  
      5.         threading.Thread.__init__(self,name = threadname)  
      6.     def run(self):  
      7.         global event  
      8.         if event.isSet():  
      9.             event.clear()  
      10.             event.wait()   #當(dāng)event被標(biāo)記時(shí)才返回  
      11.             print self.getName()  
      12.         else:  
      13.             print self.getName()  
      14.             event.set()  
      15. event = threading.Event()  
      16. event.set()  
      17. t1 = []  
      18. for i in range(10):  
      19.     t = mythread(str(i))  
      20.     t1.append(t)  
      21. for i in t1:  
      22.     i.start()  

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多