# 多進程調用(大部分與多線程的操做同樣) # 調用方式1 from multiprocessing import Process import time def f(name): time.sleep(1) print('hello', name, time.ctime()) if __name__ == '__main__': p_list = [] for i in range(3): p = Process(target=f, args=('alex',)) p_list.append(p) p.start() for i in p_list: i.join() print('end') # 調用方式2 from multiprocessing import Process import time class MyProcess(Process): # def __init__(self): # super(MyProcess, self).__init__() # self.name = name def run(self): time.sleep(1) print('hello', self.name, time.ctime()) if __name__ == '__main__': p_list = [] for i in range(3): p = MyProcess() # p.daemon = True # 設置守護進程 p.start() p_list.append(p) # for i in p_list: # i.join() print('end...') # 查看進程的pid from multiprocessing import Process import os, time def info(title): print('title:', title) print('parent process:', os.getppid()) print('process id:', os.getpid()) def f(name): info('function f') print('hello', name) if __name__ == '__main__': info('main process line') time.sleep(1) print('-' * 30) p = Process(target=info, args=('alex',)) p.start() p.join() # title: main process line # parent process: 1792 # 父進程的進程pid(pycharm) # process id: 4116 # 當前.py文件運行的pid # ------------------------------ # title: alex # parent process: 4116 # 父進程的pid即當前.py文件運行的pid # process id: 6392 # 產生的子進程的pid
# Process類的方法與屬性 # 構造方法: # Process(group[, target[, name[, args[, kwargs]]]]) # group: 線程組,目前尚未實現,庫引用中提示必須是None # target: 要執行的方法 # name: 指定進程名 # args / kwargs: 要傳入方法的參數 # # 實例方法: # is_alive() 返回進程是否在運行 # join([timeout]) 阻塞當前上下文環境的進程,直到調用此方法的進程終止或到達指定的timeout # start() 進行準備就緒,等待cpu調度 # run() start()方法調用run方法,若是實例進程時未制定傳入target,這start執行默認run方法 # terminate() 無論任務是否完成,當即中止工做進程 # # 屬性: # daemon 和線程的setDaemon功能同樣 # name 進程名字 # pid 進程號 from multiprocessing import Process import time class MyProcess(Process): def __init__(self, num): super(MyProcess, self).__init__() self.num = num def run(self): time.sleep(1) print(self.is_alive(), self.num, self.pid) time.sleep(1) if __name__ == '__main__': p_list = [] for i in range(10): p = MyProcess(i) p_list.append(p) for p in p_list: p.start() print('main process end')