在Python中我們主要是通過thread和threading這兩個模塊來實現的,其中Python的threading模塊是對thread做了一些包裝的,可以更加方便的被使用,所以我們使用threading模塊實現多線程編程。一般來說,使用線程有兩種模式,一種是創建線程要執行的函數,把這個函數傳遞進Thread對象里,讓它來執行;另一種是直接從Thread繼承,創建一個新的class,把線程執行的代碼放到這個新的 class里。
將函數傳遞進Thread對象
'''
Created on 2012-9-5
@author: walfred
@module: thread.ThreadTest1
@description:
'''
import threading
def thread_fun(num):
for n in range(0, int(num)):
print " I come from %s, num: %s" %( threading.currentThread().getName(), n)
def main(thread_num):
thread_list = list();
# 先創建線程對象
for i in range(0, thread_num):
thread_name = "thread_%s" %i
thread_list.append(threading.Thread(target = thread_fun, name = thread_name, args = (20,)))
# 啟動所有線程
for thread in thread_list:
thread.start()
# 主線程中等待所有子線程退出
for thread in thread_list:
thread.join()
if __name__ == "__main__":
main(3)
程序啟動了3個線程,并且打印了每一個線程的線程名字,這個比較簡單吧,處理重復任務就派出用場了,下面介紹使用繼承threading的方式;
繼承自threading.Thread類
'''
Created on 2012-9-6
@author: walfred
@module: thread.ThreadTest2
'''
import threading
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self);
def run(self):
print "I am %s" %self.name
if __name__ == "__main__":
for thread in range(0, 5):
t = MyThread()
t.start()
接下來的文章,將會介紹如何控制這些線程,包括子線程的退出,子線程是否存活及將子線程設置為守護線程(Daemon)。