本文實例講述了python開發(fā)之thread線程基礎(chǔ)。分享給大家供大家參考,具體如下:
說到線程,我們要知道啥是串行,啥是并行程序
舉個例子:
串行程序,就是一個一個的執(zhí)行程序
#python threadingimport time''' 每一秒中,輸出:this is a demo!'''def serial(): '''串行輸出''' time.sleep(1) print('this is a demo!')def main(): for i in range(5): serial()if __name__ == '__main__': main()運行結(jié)果如下:
>>> this is a demo!this is a demo!this is a demo!this is a demo!this is a demo!>>>
并行程序,就是很多個程序在同一時間(宏觀)一起執(zhí)行
#python threadingimport threadingimport time''' 并行執(zhí)行,輸出:Good!Good!Good!Good!Good!'''def parallel(): '''并行輸出''' time.sleep(1) print('Good!')def main(): for i in range(5): t = threading.Thread(target=parallel) t.start()if __name__ == '__main__': main()當然我們通過執(zhí)行程序,可以知道,并行程序要比串行程序執(zhí)行的要快....
我們也可以獲取到當前的線程及個數(shù):
#python threadingimport threadingimport time''' 并行執(zhí)行,輸出: [<Thread(Thread-2, started 3480)>, <Thread(Thread-1, started 660)>, <Thread(SockThread, started daemon 2920)>, <Thread(Thread-3, started 916)>, <Thread(Thread-4, started 3476)>, <_MainThread(MainThread, started 3964)>, <Thread(Thread-5, started 2060)>] 存在的線程數(shù) : 7 Good!Good!Good!Good!Good!'''def parallel(): '''并行輸出''' time.sleep(1) print('Good!')def main(): for i in range(5): t = threading.Thread(target=parallel) t.start()if __name__ == '__main__': main() print(threading.enumerate()) print('存在的線程數(shù) : %d'%threading.active_count())運行結(jié)果如下:
>>> [<Thread(SockThread, started daemon 15424)>, <Thread(Thread-3, started 15840)>, <Thread(Thread-1, started 10884)>, <Thread(Thread-2, started 14512)>, <Thread(Thread-4, started 13204)>, <_MainThread(MainThread, started 12924)>, <Thread(Thread-5, started 15476)>]存在的線程數(shù) : 7>>> Good!Good!Good!Good!Good!
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選