python多程序———9、multiprocessing多程序程式設計
阿新 • • 發佈:2018-11-12
python多程序的multiprocessing的用法跟多執行緒threading的用法基本差不多,直接上程式碼吧
import multiprocessing import os import time #fork()只能在linux中使用 # pid = os.fork() # if pid == 0: # print("子程序{},父程序是{}".format(os.getpid(),os.getppid())) # else: # print("我是父程序:{}".format(pid)) # time.sleep(2) def get_html(n): time.sleep(n) print("sub_processing success!") return n if __name__ == "__main__": # progress = multiprocessing.Process(target=get_html,args=(2,)) # print(progress.pid) # progress.start() # progress.join() # print("mian progress end") #如何使用multiprocessing中程序池 pool = multiprocessing.Pool(multiprocessing.cpu_count()) # result = pool.apply_async(get_html,args=(3,)) # pool.close() # pool.join() # print(result.get()) #imap and imap_unordered for result in pool.imap_unordered(get_html,[1,3,2,4]): print("{} sleep success!".format(result))