python中threading模块详解
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                python中threading模块详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                轉載自 ? ? ??http://blog.chinaunix.net/uid-27571599-id-3484048.html
?threading提供了一個比thread模塊更高層的API來提供線程的并發性。這些線程并發運行并共享內存。?
????? ??下面來看threading模塊的具體用法:?
 
 
? ? ?一、Thread的使用 目標函數可以實例化一個Thread對象,每個Thread對象代表著一個線程,可以通過start()方法,開始運行。
? ? ?這里對使用多線程并發,和不適用多線程并發做了一個比較:
首先是不使用多線程的操作:
 代碼如下:
 
| 1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/python #compare for multi threads import time def worker(): ????print "worker" ????time.sleep(1) ????return if __name__ == "__main__": ????for i in xrange(5): ????????worker() | 
執行結果如下:
???
下面是使用多線程并發的操作:
代碼如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 | #!/usr/bin/python import threading import time def worker(): ????print "worker" ????time.sleep(1) ????return for i in xrange(5): ????t = threading.Thread(target=worker) ????t.start() | 
可以明顯看出使用了多線程并發的操作,花費時間要短的很多。
 
 
二、threading.activeCount()的使用,此方法返回當前進程中線程的個數。返回的個數中包含主線程。
代碼如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #!/usr/bin/python #current's number of threads import threading import time def worker(): ????print "test" ????time.sleep(1) for i in xrange(5): ????t = threading.Thread(target=worker) ????t.start() print "current has %d threads" % (threading.activeCount() - 1) | 
 
 
三、threading.enumerate()的使用。此方法返回當前運行中的Thread對象列表。
代碼如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #!/usr/bin/python #test the variable threading.enumerate() import threading import time def worker(): ????print "test" ????time.sleep(2) threads = [] for i in xrange(5): ????t = threading.Thread(target=worker) ????threads.append(t) ????t.start() for item in threading.enumerate(): ????print item print for item in threads: ????print item | 
 
 
四、threading.setDaemon()的使用。設置后臺進程。
代碼如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/python #create a daemon import threading import time def worker(): ????time.sleep(3) ????print "worker" t=threading.Thread(target=worker) t.setDaemon(True) t.start() print "haha" | 
可以看出worker()方法中的打印操作并沒有顯示出來,說明已經成為后臺進程。
總結
以上是生活随笔為你收集整理的python中threading模块详解的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 关闭sublime更新提示
- 下一篇: python聊天程序
