一.多線程學習
python提供了兩個模組來實現多線程thread 和threading ,thread 有一些缺點,在threading 得到了彌補。所以我們直接學習threading即可。 建立線程:t=threading.Thread(target=函數名,args=(u'',u'',...)) 啟動線程:t.start()
二.threading的setDaemon、join的用法
1.t.setDaemon(True)
主線程A中,建立了子線程B,並且在主線程A中調用了B.setDaemon(True),這個的意思是,把主線程A設定為守護線程,這時候,要是主線程A執行結束了,就不管子線程B是否完成,一併和主線程A退出
2.t.join()
主線程A中,建立了子線程B,並且在主線程A中調用了B.join(),那麼,主線程A會在調用的地方等待,直到子線程B完成操作後,才可以接著往下執行
註:join([timeout]) 裡面的參數時可選的,代表線程啟動並執行最大時間,即如果超過這個時間,不管這個此線程有沒有執行完畢都會被回收,然後主線程或函數都會接著執行的。
import threadingfrom time import ctime,sleepdef music(name,age): for i in range(3): print "i was listening %s %s %s" %(name,age,ctime()) sleep(2)def move(address): for i in range(3): print "i was at %s %s" %(address,ctime()) sleep(5)threads=[]t1=threading.Thread(target=music,args=(u'love',u'age'))threads.append(t1)t2=threading.Thread(target=move,args=(u'shuyang',))threads.append(t2)if __name__=='__main__': for t in threads: t.setDaemon(True) t.start() print "all over %s" %ctime()