1. 程式人生 > >開啟多程序的方式

開啟多程序的方式

第一種:建立Process物件

import os,time
from multiprocessing import Process
def func(arg1,arg2):
    print("*"*arg1)
    # print("程序號:",os.getpid())
    # print("父程序:",os.getppid())
    time.sleep(0.01)
    print("="*arg2)

if __name__ == '__main__':
    p_lst = []
    for i in range(1,11):
        p = Process(target=func,args=(10*i,20*i))
        p_lst.append(p)
        p.start()
    [p.join() 
for p in p_lst] print("game over")

第二種:建立自定義類並繼承Process類,必須實現run方法,程序啟動自動呼叫run方法

import os
from multiprocessing import Process
class MyProcess(Process):
    def __init__(self,arg1,arg2):
        super().__init__()
        self.arg1 = arg1
        self.arg2 = arg2
    def run(self):
        
print(os.getpid()) if __name__ == '__main__': p1 = MyProcess(1,2) p1.start() p2 = MyProcess(3,4) p2.start() print("主程序:",os.getpid())