多執行緒與多行程的概念請自行搜尋補充,這裡力圖用最簡單的例子,讓你對 Python 多執行緒有個直觀的初步認識。
在 MS-DOS 那個年代,作業系統處理問題都是單任務的——想同時聽音樂和看電影,一定得先排個順序。
from time import ctime, sleep
def music():
for i in range(2):
print "I was listening to music. %s" % ctime()
sleep(1)
def move():
for i in range(2):
print "I was at the movies! %s" % ctime()
sleep(5)
if __name__ == '__main__':
music()
move()
print "all over %s" % ctime()
我們先聽了兩次音樂(每次 1 秒),接著看了兩場電影(每場 5 秒),全部結束後印出時間。
執行結果:
I was listening to music. Thu Apr 17 10:47:08 2014
I was listening to music. Thu Apr 17 10:47:09 2014
I was at the movies! Thu Apr 17 10:47:10 2014
I was at the movies! Thu Apr 17 10:47:15 2014
all over Thu Apr 17 10:47:20 2014
其實 music() 和 move() 更應該被看作「播放器」,至於播什麼由呼叫時決定。於是改造一下,加上參數:
#coding=utf-8
import threading
from time import ctime, sleep
def music(func):
for i in range(2):
print "I was listening to %s. %s" % (func, ctime())
sleep(1)
def move(func):
for i in range(2):
print "I was at the %s! %s" % (func, ctime())
sleep(5)
if __name__ == '__main__':
music(u'愛情買賣')
move(u'阿凡達')
print "all over %s" % ctime()
執行結果:
I was listening to 愛情買賣. Thu Apr 17 11:48:59 2014
I was listening to 愛情買賣. Thu Apr 17 11:49:00 2014
I was at the 阿凡達! Thu Apr 17 11:49:01 2014
I was at the 阿凡達! Thu Apr 17 11:49:06 2014
all over Thu Apr 17 11:49:11 2014
CPU 越來越快,它抱怨「P 大一點事兒占我一整個時間單,其實我同時幹多個活都沒問題」,於是作業系統進入了多任務時代。
Python 提供 thread 與 threading 兩個模組,thread 有一些缺點並在 threading 中得到彌補,所以直接學 threading 就好。
#coding=utf-8
import threading
from time import ctime, sleep
def music(func):
for i in range(2):
print "I was listening to %s. %s" % (func, ctime())
sleep(1)
def move(func):
for i in range(2):
print "I was at the %s! %s" % (func, ctime())
sleep(5)
threads = []
t1 = threading.Thread(target=music, args=(u'愛情買賣',))
threads.append(t1)
t2 = threading.Thread(target=move, args=(u'阿凡達',))
threads.append(t2)
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
print "all over %s" % ctime()
逐段解讀:
import threading:使用多執行緒的前提。threads = [] 與 threading.Thread(target=music, args=(u'愛情買賣',)):建立 threads 陣列,target 指定要跑的方法,args 負責傳參,再把 t1 裝進陣列;t2 同理。setDaemon(True):把執行緒宣告為守護執行緒,必須在 start() 之前設定,否則程式會被無限掛起。子執行緒啟動後父執行緒繼續往下跑,父執行緒執行完最後一句就退出,子執行緒也跟著結束。start():開始執行緒活動。執行結果:
I was listening to 愛情買賣. Thu Apr 17 12:51:45 2014 I was at the 阿凡達! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014
可見子執行緒與主執行緒同時啟動,但主執行緒跑完就結束,子執行緒也被一起終止。
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start()
t.join()
print "all over %s" % ctime()
join() 用來等待執行緒終止:在子執行緒完成之前,它的父執行緒會一直被阻塞。注意這裡 join() 放在 for 迴圈外面,也就是必須等迴圈裡的兩個執行緒都結束後,才去執行主行程。
執行結果:
I was listening to 愛情買賣. Thu Apr 17 13:04:11 2014 I was at the 阿凡達! Thu Apr 17 13:04:11 2014
I was listening to 愛情買賣. Thu Apr 17 13:04:12 2014
I was at the 阿凡達! Thu Apr 17 13:04:16 2014
all over Thu Apr 17 13:04:21 2014
music 與 move 同時啟動,總耗時 10 秒,比單執行緒少了 2 秒。把 music 的 sleep 從 1 秒調成 4 秒再試:
I was listening to 愛情買賣. Thu Apr 17 13:11:27 2014I was at the 阿凡達! Thu Apr 17 13:11:27 2014
I was listening to 愛情買賣. Thu Apr 17 13:11:31 2014
I was at the 阿凡達! Thu Apr 17 13:11:32 2014
all over Thu Apr 17 13:11:37 2014
子執行緒 11 分 27 秒啟動,主行程 11 分 37 秒結束。雖然 music 每首歌從 1 秒延長到 4 秒,但因為是並行執行,總時間沒有變化——這就是多執行緒最直觀的價值。
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
若子類覆寫了構造器,必須先呼叫基類構造器 Thread.__init__(),再做其他事。
無需操作系統直接運行 Python 代碼 https://www.linuxidc.com/Linux/2015-05/117357.htm
CentOS 上源碼安裝 Python3.4 https://www.linuxidc.com/Linux/2015-01/111870.htm
《Python核心編程 第二版》.(Wesley J. Chun).[高清PDF中文版] https://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.(周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] https://www.linuxidc.com/Linux/2013-11/92693.htm
Python 腳本獲取 Linux 系統信息 https://www.linuxidc.com/Linux/2013-08/88531.htm
在 Ubuntu 下用 Python 搭建桌面算法交易研究環境 https://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 https://www.linuxidc.com/Linux/2014-09/107206.htm
更多詳情見請繼續閱讀下一頁的精彩內容: https://www.linuxidc.com/Linux/2015-06/119279p2.htm