1. 程式人生 > >python併發程序

python併發程序

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 20 23:23:35 2018
#QQ群:476842922(歡迎加群討論學習)
@author: Administrator
"""
#coding: utf-8
import multiprocessing
import time
 
def func(msg):
    print("msg:", msg)
    time.sleep(3)
    print("end")
    return msg
 
if __name__ == "__main__":
    cores =
multiprocessing.cpu_count()#返回當前系統有多少個CPU pool = multiprocessing.Pool(processes=cores)#建立cores程序池 print("Adding tasks...") results = [] for i in range(cores): msg = "hello %d" %(i) results.append(pool.apply_async(func, (msg, ))) #維持執行的程序總數為processes,當一個程序執行完畢後會新增新的程序進去
print("Starting tasks...") pool.close() pool.join() #呼叫join之前,先呼叫close函式,否則會出錯。執行完close後不會有新的程序加入到pool,join函式等待所有子程序結束 print([r.get() for r in results]) print("Sub-process(es) done.")

Adding tasks…
Starting tasks…
[‘hello 0’, ‘hello 1’, ‘hello 2’, ‘hello 3’, ‘hello 4’, ‘hello 5’, ‘hello 6’, ‘hello 7’]
Sub-process(es) done.