Python建立程序、執行緒的兩種方式
阿新 • • 發佈:2020-08-08
程式碼建立程序和執行緒的兩種方式
"""
定心丸:Python建立程序和執行緒的方式基本都是一致的,包括其中的呼叫方法等,學會一個
另一個自然也就會了。
"""
1.建立程序的兩種方式
-
方式一
import os import time from multiprocessing import Process # 例項化一個multiprocessing.Process的物件,並傳入一個初始化函式物件 def task(name): print(f'程序 {name} 的PID為{os.getpid()},父程序ID為 {os.getppid()}') time.sleep(2) print(f'程序 {name} 的PID為{os.getpid()} 執行結束') if __name__ == '__main__': # 此處要注意,windows下開啟程序一定要在main方法下開啟 process1 = Process(target=task, args=('1',)) process2 = Process(target=task, args=('2',)) # 啟動程序 process1.start() # 告訴作業系統幫你建立一個程序 process2.start() print(f'主程序 {os.getpid()}')
-
方式二
import os import time from multiprocessing import Process # 繼承類的方式去建立 class MyProcess(Process): def __init__(self, name): # 繼承Process中的__init__() super(MyProcess, self).__init__() self.name = name # 此處必要在該類中建立run方法 重寫run方法 def run(self): print(f'程序 {self.name} 的PID為{os.getpid()},父程序ID為 {os.getppid()}') time.sleep(2) print(f'程序 {self.name} 的PID為{os.getpid()} 執行結束') if __name__ == '__main__': # 建立兩個程序 process1 = MyProcess('1') process2 = MyProcess('2') # 開啟這兩個程序 process1.start() process2.start() print(f'主程序 {os.getpid()}')
執行結果如下:
""" 主程序 2776 程序 1 的PID為9364,父程序ID為 2776 程序 2 的PID為4140,父程序ID為 2776 程序 1 的PID為9364 執行結束程序 2 的PID為4140 執行結束 """
2.建立執行緒的兩種方式
-
方式一
import time from threading import Thread # 例項化一個multiprocessing.Process的物件,並傳入一個初始化函式物件 def task(name): print(f"執行緒 {name} is running") time.sleep(2) print(f"執行緒 {name} is over") if __name__ == '__main__': # 開啟執行緒不需要在main下面執行程式碼,直接書寫就可以 # 但是還是習慣性的將啟動命令寫在main下面 # 建立兩個執行緒 thead1 = Thread(target=task, args=('1',)) thead2 = Thread(target=task, args=('2',)) # 開啟兩個執行緒 thead1.start() # 建立執行緒的開銷非常小,幾乎程式碼一執行執行緒就建立了 thead2.start() print("主")
-
方式二
import time from threading import Thread # 繼承類的方式去建立 class MyThead(Thread): def __init__(self, name): # 繼承Process中的__init__() super(MyThead, self).__init__() self.name = name # 此處必要在該類中建立run方法 重寫run方法 def run(self): print(f"執行緒 {self.name} is running") time.sleep(2) print(f"執行緒 {self.name} is over") if __name__ == '__main__': # 建立兩個執行緒 thead1 = MyThead('1') thead2 = MyThead('1') # 開啟這兩個執行緒 thead1.start() thead2.start() print('主')
-
輸出結果為如下:
""" 執行緒 1 is running 主 執行緒 2 is running 執行緒 1 is over執行緒 2 is over """
上方只是簡單的建立程序和執行緒,以上註釋只是個人理解,不足的地方還望見諒,歡迎補充