# coding:utf-8
import os
import time
from multiprocessing import Pool
def func(n):
print("%s:%s" % (os.getpid(), n))
return n**2
def func2(n):
print("%s:%s" % (os.getpid(), n))
time.sleep(1)
return n**2
if __name__ == '__main__':
start_time = time.time()
the pool = Pool (5) # from scratch to create 5 processes the process pool, after this has been in the process of five tasks
res_lst = []
for i in the Range (10 ):
RES = pool.apply_async (FUNC, args = (i,)) # asynchronous operation, according to the number of processes some processes in the pool with a maximum of three sub-processes in asynchronous execution and can perform different tasks, transfer any of the parameters.
# After returning results, it will result into a list of the restitution process, after then perform a new task
# Note that, the pool will not process three processes simultaneously open or end at the same time
# but would release a complete implementation of a process this process went to receive new tasks.
res_lst.append (RES)
# asynchronous apply_async Usage: If using asynchronous tasks submitted, the main process requires the use of join, wait for the process tanks tasks are processed, the results can then be collected using GET
# Otherwise, the end of the primary process, the process may not have the pool enough time to perform, also followed the end together
pool.close () # is not a closed process pool, but the pool end of the process to receive the task to ensure that no new tasks before submitting over.
pool.join () # perceptual task execution process pool has ended, only when there is no new task is added to come in order to perceive the mission is over, it must be coupled with close method before the Join
Print ([r.get ( ) for r in res_lst]) # using get to get the result apply_aync, and if so apply, the method does not get as apply synchronous execution, and immediately get results, but also did not need to get
Print ( " execution time non-blocking program: " , time.time () - start_time)
S_TIME = time.time ()
POOL2 = pool (5) # from scratch to create 5 processes the process pool, after this has been in the process of five tasks
res_lst = []
for I in Range (10 ):
RES = pool2.apply_async (func2, args = (I,))
res_lst.append (RES)
pool2.close ()
pool2.join ()
Print ([r.get () for r in res_lst])
Print ( " There is a block of program execution time: " , time.time () - S_TIME)
# 8860: 0
# 8860: 1
# 8860: 2
# 8860: 3
# 8860: 4
# 8860: 5
# 8860: 6
# 8860: 7
# 8860: 8
# 8860: 9
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# execution time of the program nonblocking: 0.609375
# 7728: 0
# 3668: 1
# 7288: 2
# 8300: 3
# 10168: 4
# 7728: 5
# 3668: 6
# 7288: 7
# 8300: 8
# 10168: 9
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# obstructions program execution time: 2.625