python是支援多線程的,並且是native的線程。主要是通過thread和threading這兩個模組來實現的。thread是比較底層的模組,threading是對thread做了一些封裝的,可以更加方便的被使用。這裡需要提一下的是python對線程的支援還不夠完善,不能利用多CPU,但是下個版本的python中已經考慮改進這點,讓我們拭目以待吧。
threading模組裡面主要是對一些線程的操作對象化了,建立了叫Thread的class。一般來說,使用線程有兩種模式,一種是建立線程要執行的函數,把這個函數傳遞進Thread對象裡,讓它來執行;另一種是直接從Thread繼承,建立一個新的class,把線程執行的代碼放到這個新的class裡。我們來看看這兩種做法吧。
#-*- encoding: gb2312 -*-import string, threading, timedef thread_main(a): global count, mutex # 獲得線程名 threadname = threading.currentThread().getName() for x in xrange(0, int(a)): # 取得鎖 mutex.acquire() count = count + 1 # 釋放鎖 mutex.release() print threadname, x, count time.sleep(1) def main(num): global count, mutex threads = [] count = 1 # 建立一個鎖 mutex = threading.Lock() # 先建立線程對象 for x in xrange(0, num): threads.append(threading.Thread(target=thread_main, args=(10,))) # 啟動所有線程 for t in threads: t.start() # 主線程中等待所有子線程退出 for t in threads: t.join() if __name__ == '__main__': num = 4 # 建立4個線程 main(4)
上面的就是第一種做法,這種做法是很常見的,下面是另一種,曾經使用過Java的朋友應該很熟悉這種模式:
#-*- encoding: gb2312 -*-import threadingimport timeclass Test(threading.Thread): def __init__(self, num): threading.Thread.__init__(self) self._run_num = num def run(self): global count, mutex threadname = threading.currentThread().getName() for x in xrange(0, int(self._run_num)): mutex.acquire() count = count + 1 mutex.release() print threadname, x, count time.sleep(1)if __name__ == '__main__': global count, mutex threads = [] num = 4 count = 1 # 建立鎖 mutex = threading.Lock() # 建立線程對象 for x in xrange(0, num): threads.append(Test(10)) # 啟動線程 for t in threads: t.start() # 等待子線程結束 for t in threads: t.join()