import threading
import time
def target():
print 'the curent threading %s is running' % threading.current_thread().name #獲取線程名稱
time.sleep(1)
print 'the curent threading %s is ended' % threading.current_thread().name
print 'the curent threading %s is running' % threading.current_thread().name
t = threading.Thread(target=target)
t.start()
t.join()
print 'the curent threading %s is ended' % threading.current_thread().name
輸出:
the curent threading MainThread is running
the curent threading Thread-1 is running
the curent threading Thread-1 is ended
the curent threading MainThread is ended
start是啟動(dòng)線程join是阻塞當(dāng)前線程即使得在當(dāng)前線程結(jié)束時(shí)撇贺,不會(huì)退出押蚤。從結(jié)果可以看到耸彪,主線程直到Thread-1結(jié)束之后才結(jié)束隘世。
如果不加join語(yǔ)句筒扒,那么主線程不會(huì)等到當(dāng)前線程結(jié)束才結(jié)束怯邪,但卻不會(huì)立即殺死該線程。如不加join輸出如下
但如果為線程實(shí)例添加t.setDaemon(True)之后花墩,如果不加join語(yǔ)句悬秉,那么當(dāng)主線程結(jié)束之后,會(huì)殺死子線程如果加上join,并設(shè)置等待時(shí)間冰蘑,就會(huì)等待線程一段時(shí)間再退出
map實(shí)現(xiàn)多線程
urls = ['http://www.baidu.com','http://www.sina.com','http://www.qq.com']
results=map(urllib.requests.urlopen,urls)
在 Python 中有個(gè)兩個(gè)庫(kù)包含了 map 函數(shù): multiprocessing 和它鮮為人知的子庫(kù) multiprocessing.dummy.dummy 是 multiprocessing 模塊的完整克隆和泌,唯一的不同在于 multiprocessing 作用于進(jìn)程,而 dummy 模塊作用于線程祠肥。代碼:
import urllib
import requests
from multiprocessing.dummy import Pool as ThreadPool
urls = ['http://www.baidu.com','http://www.sina.com','http://www.qq.com']
pool = ThreadPool()
results = pool.map(urllib.requests.urlopen,urls)
print results
pool.close()
pool.join()
print 'main ended'
- pool = ThreadPool()創(chuàng)建了線程池武氓,其默認(rèn)值為當(dāng)前機(jī)器 CPU 的核數(shù),可以指定線程池大小仇箱,不是越多越好县恕,因?yàn)樵蕉嗟脑挘€程之間的切換也是很消耗資源的剂桥。
- results = pool.map(urllib2.urlopen,urls) 該語(yǔ)句將不同的url傳給各自的線程忠烛,并把執(zhí)行后結(jié)果返回到results中。