关于python的单线程和多线程
生活随笔
收集整理的這篇文章主要介紹了
关于python的单线程和多线程
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
單線程
比如兩件事,要相繼執(zhí)行,而不是一起執(zhí)行
'''學(xué)習(xí)一下單線程和多線程的問題'''from time import ctime,sleep '''單線程''' print('單線程開始:') def music_single(name):for i in range(2):print('i was listening to music %s. %s' %(name,ctime()))sleep(1) def move_single(name):for i in range(2):print('i was at the movies %s! %s' %(name,ctime()))sleep(5) if __name__=="__main__":music_single(u'夜空中最亮的星')move_single(u'諜影重重')print('all over %s' %ctime())輸出結(jié)果:
單線程開始: i was listening to music 夜空中最亮的星. Mon Aug 27 21:24:03 2018 i was listening to music 夜空中最亮的星. Mon Aug 27 21:24:04 2018 i was at the movies 諜影重重! Mon Aug 27 21:24:05 2018 i was at the movies 諜影重重! Mon Aug 27 21:24:10 2018 all over Mon Aug 27 21:24:15 2018多線程
即邊聽歌邊看電影,python中有thread和threading用來實現(xiàn)多線程,在這里使用threading。
'''多線程''' print('****************') print('多線程開始:') from time import ctime,sleep import threadingdef music_mutil(name):for i in range(2):print('i was listening to music %s. %s' %(name,ctime()))sleep(1) def move_mutil(name):for i in range(2):print('i was at the movies %s! %s' %(name,ctime()))sleep(5)threads=[] t1=threading.Thread(target=music_mutil,args=(u'夜空中最亮的星',)) # 創(chuàng)建線程t1 threads.append(t1) t2=threading.Thread(target=move_mutil,args=(u'諜影重重',)) # 創(chuàng)建線程t2 threads.append(t2)if __name__=='__main__':for t in threads: # 遍歷線程數(shù)組t.setDaemon(True) # 將線程聲明為守護(hù)線程,必須在start()之前設(shè)置,如果不設(shè)置為守護(hù)線程,那么程序會被無限掛起。t.start() # 開始線程 t.join()print('all over %s' %ctime())輸出結(jié)果:
**************** 多線程開始: i was listening to music 夜空中最亮的星. Mon Aug 27 21:24:15 2018 i was at the movies 諜影重重! Mon Aug 27 21:24:15 2018 i was listening to music 夜空中最亮的星. Mon Aug 27 21:24:16 2018 i was at the movies 諜影重重! Mon Aug 27 21:24:20 2018 all over Mon Aug 27 21:24:25 2018注意:
倘若沒有join()語句,那么輸出結(jié)果為
分析:
以上,從運行結(jié)果看,子線程(music_mutil,move_mutil)和主線程(print(all over %s) %ctime())一起啟動,但是主線程結(jié)束導(dǎo)致子線程也終止。在這里可以在主線程前面加上t.join(),其作用是在子線程完成運行之前,子線程的父線程將一直被阻塞。注意,join()的位置是在for循環(huán)外的,也就是說必須等待for循環(huán)里的兩個進(jìn)程都結(jié)束后,才去執(zhí)行主進(jìn)程。
多線程進(jìn)階
重寫一下代碼,寫一個player,根據(jù)文件類型來選擇操作。
from time import ctime,sleep import threadingdef music(name):for i in range(2):print('start playing %s. %s' %(name,ctime()))sleep(2)def move(name):for i in range(2):print('start playing %s. %s' %(name,ctime()))sleep(5)def player(func):rc=func.split('.')[1]if rc=='mp3':music(func)else:if rc=='mp4':move(func)else:print('error type of file!')alist=['夜空中最亮的星.mp3','諜影重重.mp4'] length=len(alist) threads=[] # 創(chuàng)建線程 for i in range(length):t=threading.Thread(target=player,args=(alist[i],))threads.append(t) if __name__=='__main__':# 啟動線程for i in range(length):threads[i].start()for i in range(length):threads[i].join()# 主線程print('all over at %s' %(ctime()))輸出:
start playing 夜空中最亮的星.mp3. Mon Aug 27 21:52:50 2018 start playing 諜影重重.mp4. Mon Aug 27 21:52:50 2018 start playing 夜空中最亮的星.mp3. Mon Aug 27 21:52:52 2018 start playing 諜影重重.mp4. Mon Aug 27 21:52:55 2018 all over at Mon Aug 27 21:53:00 2018繼續(xù)修改:
from time import ctime,sleep import threadingdef super_player(name,time0):for i in range(2):print('now we are playing %s. %s' %(name,ctime()))sleep(time0) # alist={'飛鳥.mp3':3,'阿凡達(dá).mp4':4,'我和你.mp3':4}threads=[] files=range(len(alist))# 創(chuàng)建線程 for file,time in alist.items():t=threading.Thread(target=super_player,args=(file,time))threads.append(t)if __name__=='__main__':# 啟動線程for i in files:threads[i].start()for i in files:threads[i].join()# 主線程print('end: %s' %ctime())輸出:
now we are playing 飛鳥.mp3. Mon Aug 27 21:57:02 2018 now we are playing 阿凡達(dá).mp4. Mon Aug 27 21:57:02 2018 now we are playing 我和你.mp3. Mon Aug 27 21:57:02 2018 now we are playing 飛鳥.mp3. Mon Aug 27 21:57:05 2018 now we are playing 我和你.mp3. Mon Aug 27 21:57:06 2018 now we are playing 阿凡達(dá).mp4. Mon Aug 27 21:57:06 2018 end: Mon Aug 27 21:57:10 2018繼續(xù)創(chuàng)建:
'''創(chuàng)建自己的多線程類'''#coding=utf-8 import threading from time import sleep,ctimeclass MyThread(threading.Thread):def __init__(self,func,args,name=''):threading.Thread.__init__(self)self.name=nameself.func=funcself.args=argsdef run(self):# apply(self.func,self.args) # python2的用法self.func(*self.args) # python3沒有了apply()的全局用法。用self.func(*self.args)。def super_play(file,time):for i in range(2):print('start playing: %s! %s' %(file,ctime()))sleep(time)alist={'紅日.mp3':3,'阿凡達(dá).mp4':5}# 創(chuàng)建線程 threads=[] files=range(len(alist))for k,v in alist.items():t=MyThread(super_play,(k,v),super_play.__name__)threads.append(t)if __name__=='__main__':# 啟動線程for i in files:threads[i].start()for i in files:threads[i].join()# 主線程print('end: %s' %ctime())輸出:
start playing: 紅日.mp3! Mon Aug 27 21:58:48 2018 start playing: 阿凡達(dá).mp4! Mon Aug 27 21:58:48 2018 start playing: 紅日.mp3! Mon Aug 27 21:58:51 2018 start playing: 阿凡達(dá).mp4! Mon Aug 27 21:58:53 2018 end: Mon Aug 27 21:58:58 2018轉(zhuǎn)載于:https://www.cnblogs.com/rayshaw/p/9544807.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的关于python的单线程和多线程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c/c++ 模板与STL小例子系列一 自
- 下一篇: 如何检查无线路由器是否坏了 如何测量无线