多線程threading模塊用法 -《狗嗨默示錄》-

threading提供了一個比thread模塊更高層的API來提供線程的併發性。這些線程併發運行並共享內存。 python

        下面來看threading模塊的具體用法: 多線程

 

     1、Thread的使用 目標函數能夠實例化一個Thread對象,每一個Thread對象表明着一個線程,能夠經過start()方法,開始運行。併發

     這裏對使用多線程併發,和不適用多線程併發作了一個比較:app

首先是不使用多線程的操做:函數

代碼以下:spa

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#compare for multi threads import time def worker(): print "worker" time.sleep(1) return if __name__ == "__main__": for i in xrange(5): worker()

執行結果以下:線程

   

下面是使用多線程併發的操做:code

代碼以下:對象

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading import time def worker(): print "worker" time.sleep(1) return for i in xrange(5): t = threading.Thread(target=worker) t.start()

能夠明顯看出使用了多線程併發的操做,花費時間要短的不少。blog

 

2、threading.activeCount()的使用,此方法返回當前進程中線程的個數。返回的個數中包含主線程。

代碼以下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#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)

 

3、threading.enumerate()的使用。此方法返回當前運行中的Thread對象列表。

代碼以下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#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

 

4、threading.setDaemon()的使用。設置後臺進程。

代碼以下:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#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()方法中的打印操做並無顯示出來,說明已經成爲後臺進程。

相關文章
相關標籤/搜索