多任務可以由多進程完成,也可以由一個進程內的多線程完成。
我們前面提到了進程是由若干線程組成的,一個進程至少有一個線程。
由于線程是操作系統直接支持的執行單元,因此,高級語言通常都內置多線程的支持,Python也不例外,并且,Python的線程是真正的Posix Thread,而不是模擬出來的線程。
Python的標準庫提供了兩個模塊:thread和threading,thread是低級模塊,threading是高級模塊,對thread進行了封裝。絕大多數情況下,我們只需要使用threading這個高級模塊。
啟動一個線程就是把一個函數傳入并創建Thread實例,然后調用start()開始執行:
import time, threading# 新線程執行的代碼:def loop(): print 'thread %s is running...' % threading.current_thread().name n = 0 while n < 5: n = n + 1 print 'thread %s >>> %s' % (threading.current_thread().name, n) time.sleep(1) print 'thread %s ended.' % threading.current_thread().nameprint 'thread %s is running...' % threading.current_thread().namet = threading.Thread(target=loop, name='LoopThread')t.start()t.join()print 'thread %s ended.' % threading.current_thread().name
執行結果如下:
thread MainThread is running...thread LoopThread is running...thread LoopThread >>> 1thread LoopThread >>> 2thread LoopThread >>> 3thread LoopThread >>> 4thread LoopThread >>> 5thread LoopThread ended.thread MainThread ended.
由于任何進程默認就會啟動一個線程,我們把該線程稱為主線程,主線程又可以啟動新的線程,Python的threading模塊有個current_thread()函數,它永遠返回當前線程的實例。主線程實例的名字叫MainThread,子線程的名字在創建時指定,我們用LoopThread命名子線程。名字僅僅在打印時用來顯示,完全沒有其他意義,如果不起名字Python就自動給線程命名為Thread-1,Thread-2……
Lock
多線程和多進程最大的不同在于,多進程中,同一個變量,各自有一份拷貝存在于每個進程中,互不影響,而多線程中,所有變量都由所有線程共享,所以,任何一個變量都可以被任何一個線程修改,因此,線程之間共享數據最大的危險在于多個線程同時改一個變量,把內容給改亂了。
來看看多個線程同時操作一個變量怎么把內容給改亂了:
import time, threading # 假定這是你的銀行存款:balance = 0def change_it(n): # 先存后取,結果應該為0: global balance balance = balance + n balance = balance - ndef run_thread(n): for i in range(100000): change_it(n)t1 = threading.Thread(target=run_thread, args=(5,))t2 = threading.Thread(target=run_thread, args=(8,))t1.start()t2.start()t1.join()t2.join()print balance
新聞熱點
疑難解答