Python的進程和線程,Python進程線程
進程:作業系統分配記憶體的一個基本單位,進程之間的記憶體是相互隔離的,如果進程間要相互連信,要靠一個IPC機制 process
線程:一個進程又可以劃分為多個線程,線程是進程的執行單元,也是作業系統分配CPU的基本單元 thread
為什麼要使用多進程和多線程?
如果一個任務執行時間很長,就可以分解成多線程或多進程,
提升執行效率,改善程式效能,縮短執行時間
改善使用者體驗,讓使用者獲得更好的使用者體驗
進程
multiprocessing模組提供了一個Process類來代表一個進程對象
import timefrom multiprocessing import Processimport oscount = 0def output(string): global count while count < 10: print(string, end='', flush=True) count += 1def main(): p1 = Process(target=output, args=('Ping', )) p1.start() p2 = Process(target=output, args=('Pong',)) p2.start()多線程
多任務可以由多進程完成,也可以由一個進程內的多線程完成。
我們前面提到了進程是由若干線程組成的,一個進程至少有一個線程。
由於線程是作業系統直接支援的執行單元,因此,進階語言通常都內建多線程的支援,Python也不例外,並且,Python的線程是真正的Posix Thread,而不是類比出來的線程。
Python的標準庫提供了兩個模組:_thread和threading,_thread是低級模組,threading是進階模組,對_thread進行了封裝。絕大多數情況下,我們只需要使用threading這個進階模組。
啟動一個線程就是把一個函數傳入並建立Thread執行個體,然後調用start()開始執行
from threading import Threadcount = 0class PrintThread(Thread): def __init__(self, string, count): super().__init__() self._string = string self._count = count def run(self): for _ in range(self._count): print(self._string, end='', flush=True)def main(): PrintThread('Ping', 10).start() PrintThread('Pong', 10).start()
建立線程的兩種方式
1. 直接建立Thread對象並通過target參數指定線程啟動後要執行的任務
2. 繼承Thread自訂線程 通過重寫run方法指定線程啟動後執行的任務