python學習系列之多線程

來源:互聯網
上載者:User

一.多線程學習
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()
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.