Python 提供了multiprocessing模块来在单个系统中执行多个任务。它提供了一个用户友好和直观的 API 来处理多进程。
让我们理解多进程的简单例子。
示例-
from multiprocessing import Process defdisp(): print ('Hello !! Welcome to Python Tutorial') if __name__ == '__main__': p = Process(target=disp) p.start() p.join()
输出:
'Hello !! Welcome to Python Tutorial'
说明:
在上面的代码中,我们已经导入了 Process 类,然后在 disp() 函数中创建了 Process 对象。然后我们使用 start() 方法开始流程,并使用 join() 方法完成流程。我们也可以使用参数关键字在声明的函数中传递参数。
让我们理解下面这个带参数的多进程的例子。
示例- 2
# Python multiprocessing example # importing the multiprocessing module
import multiprocessing defcube(n): # This function will print the cube of the given number print("The Cube is: {}".format(n * n * n))
defsquare(n): # This function will print the square of the given number print("The Square is: {}".format(n * n))
if __name__ == "__main__": # creating two processes process1 = multiprocessing.Process(target= square, args=(5, )) process2 = multiprocessing.Process(target= cube, args=(5, ))
# Here we start the process 1 process1.start() # Here we start process 2 process2.start()
# The join() method is used to wait for process 1 to complete process1.join() # It is used to wait for process 1 to complete process2.join()
# Print if both processes are completed print("Both processes are finished")
输出:
The Cube is: 125 The Square is: 25 Both processes are finished
for i inrange(total_task): tasks_to_perform.put("Task no " + str(i))
# defining number of processes for w inrange(total_number_of_processes): p = Process(target=jobTodo, args=(tasks_to_perform, complete_tasks)) number_of_processes.append(p) p.start()
# completing process for p in number_of_processes: p.join()
# print the output whilenot complete_tasks.empty(): print(complete_tasks.get())
returnTrue
if __name__ == '__main__': main()
输出:
Task no 2 Task no 5 Task no 0 Task no 3 Task no 6 Task no 1 Task no 4 Task no 7 Task no 0is done by Process-1 Task no 1is done by Process-3 Task no 2is done by Process-2 Task no 3is done by Process-1 Task no 4is done by Process-3 Task no 5is done by Process-2 Task no 6is done by Process-1 Task no 7is done by Process-3
defwork_log(data_for_work): print(" Process name is %s waiting time is %s seconds" % (data_for_work[0], data_for_work[1])) time.sleep(int(data_for_work[1])) print(" Process %s Executed." % data_for_work[0])
defhandler(): p = Pool(2) p.map(work_log, w)
if __name__ == '__main__': handler()
输出:
Process name is V waiting time is5 seconds Process V Executed. Process name is X waiting time is2 seconds Process X Executed. Process name is Y waiting time is1 seconds Process Y Executed. Process name is Z waiting time is3 seconds Process Z Executed.
让我们了解多进程池的另一个例子。
示例- 2
from multiprocessing import Pool deffun(x): return x*x
if __name__ == '__main__': with Pool(5) as p: print(p.map(fun, [1, 2, 3]))