Python連載37-多程序、程序子類、程序父子id
阿新 • • 發佈:2019-09-13
一、執行緒替代方案
1.subprocess
(1)完全跳過執行緒,使用程序
(2)是派生程序的主要替代方案
(3)python2.4後引入
2.multiprocessing
(1)使用threading介面派生,使用子程序
(2)允許為多核或者多CPU派生程序,介面很threading非常相似
(3)python2.6
3.concurrent.futures
(1)新的非同步執行模組
(2)人物級別的操作
(3)python3.2之後引入
4.多程序
(1)程序間通訊(InterprocessCommunication,IPC)
(2)程序之間無任何共享狀態
(3)程序的建立
i.直接生成Process例項物件,舉例
import multiprocessing from time import sleep,ctime def clock(interval): while True: print("The time is %s" % ctime()) sleep(interval) if __name__ == "__main__": p = multiprocessing.Process(target= clock,args=(2,)) p.start() #從執行就可以看出來主程序已經結束了,但是子執行緒仍然在執行著 #和我們之前講的執行緒,有一個最大區別就是執行緒在主程序裡面,主程序結束了,子執行緒就結束了 #子執行緒從屬於程序,子程序與程序之間是並列關係 #這裡的程式停止,是我手動停止的
ii.派生子類
舉例:重寫子類,和我們之前講的執行緒的差不多,這裡民重寫了最重要的兩個函式,一個是初始化子類,繼承父類的初始化,第二個就是執行函式
class ClockProcess(multiprocessing.Process): def __init__(self,interval): super().__init__() self.interval = interval def run(self): while True: print("The time is {0}".format(ctime())) sleep(self.interval) if __name__ == "__main__": p2 = ClockProcess(2) p2.start()
iii.在os中檢視pid,ppid以及他們的關係
def info(title): print(title) print("module name:",__name__) #得到父程序的id print("parent process:",os.getppid()) #得到本身程序的id print("process id:",os.getpid()) def f(name): info("function f") print("hello",name) if __name__ == "__main__": info("main line") print("==================================") p = multiprocessing.Process(target=f,args=("bob",)) p.start() p.join()
解釋:先呼叫了一個函式,然後又呼叫了一個巢狀函式的函式
四、原始碼
d26_1_multiprocess_exercise.py
https://github.com/ruigege66/Python_learning/blob/master/d26_1_multiprocess_exercise.py
2.CSDN:https://blog.csdn.net/weixin_44630050(心悅君兮君不知-睿)
3.部落格園:https://www.cnblogs.com/ruigege0000/
4.歡迎關注微信公眾號:傅立葉變換,個人公眾號,僅用於學習交流,後臺回覆”禮包“,獲取大資料學習資料
&n