Home > other >  Python multi-process, when a child process to complete the task, how to end all processes?
Python multi-process, when a child process to complete the task, how to end all processes?

Time:10-07

The following case, if the child process p1 has found the num, p1 will be terminated, but the child p2 will continue to run, I want find num p1 and p2, stop all other child processes, how to deal with this situation?
-- -- -- -- -- -- -- -- -- -- -- -- -- --
The import multiprocessing
The import time

# traversal x-y range of Numbers, find a given num
Def foo (num, x, y) :
While x<=y:
If x==int (num) :
Print (x, 'is the number of')
Break
The else:
Print (x)
X=x + 1

If __name__=="__main__ ':
Num=input (' num=') # enter a number to find
X=0
Y=1000000
St1=time. Time () #
single process start timeFoo (num, x, y)
End1=time. Time () # single process end time


P1=multiprocessing. Process (target=foo, args=(num, x, int (y/2))) Process of # 1 traverse x ~ y/2
P2=multiprocessing. Process (target=foo, args=(num, int (y/2), y)) 2 # Process traversal y/2 ~ y
St2=time. Time () # processes start time is
P1. The start ()
P2. The start ()
P1. The join ()
P2. The join ()
End2=time. Time () # process to end more time

Print (' single process is: 'end1 - st1)
Print (' processes available: 'end2 - st2)
  • Related