(python) subprocess (use of the Process class)

Python provides the multiprocessing module to start subprocesses and execute our custom tasks in the subprocesses. A mention (the multiprocessing module has many functions, supports sub-processes, communicates, shares data, and performs different forms of synchronization. It provides Process, Queue, Pipe, Lock and other components for these.)

The class Process that creates the process:


Instantiate the Process class to get an object to start a process.

Let's take a look at its parameters:


The group parameter is not used and the value is always None.

The target represents the calling object, which is the task to be executed by the child process.

name can name the child process.

args specifies the positional parameter of the target function, which is in the form of a tuple and must have commas, such as: args=('monicx',)

kwargs specifies the keyword parameter of the target function, which is a dictionary, such as kwargs={'name':'monicx','age':18}

The methods of the Process class are:

start() : start the process and call p.run() in the child process

run(): The method for the process to start and run is to call the function specified by the target. This method must be implemented in the class of our custom class.

terminate(): Forcibly terminate the process. No cleanup operation will be performed. If p creates a child process, the child process will become a zombie process. Use this method with care: if the process also holds a lock, the lock will not be released, resulting in a deadlock. .

is_alive(): Determines whether the process is "alive".

join(timeout): Let the main thread wait for a child process to end before continuing to execute the main process. timeout is an optional timeout. The main process will not wait for more than a time.

There are two ways to create a child process:

method one:

from multiprocessing import Process
import time

def test(name):
    print("%s is running "% name)
    time.sleep(2)
    print('%s is done'%name)

if __name__ == '__main__':
    #On the windows system, the operation of starting the child process must be placed under this
    # Process(target=test,kwargs={'name':'monicx'})
    p=Process(target=test,args=('monicx',))
    p.start()# sends a request to the operating system, the operating system will apply for memory space, and then copy the data of the parent process to the child process as the initial data of the child process.
    print('========main')
The running effect is:


Method two:

from multiprocessing import Process
import time

class MyProcess(Process):
    def __init__(self,name):
        super (MyProcess, self) .__ init __ ()
        self.name=name

    def run(self):
        print("%s is running " %self.name)
        time.sleep(2)
        print('%s is done'%self.name)

if __name__ == '__main__':
    p = MyProcess ('monicx')
    p.start()# is to call the run() method.
    print('====main')

operation result:


Verify that the memory space between processes is isolated from each other.

from multiprocessing import Process
import time

x=1000

def test():
    overall x
    x=0
    print('The child process ends', x)

if __name__ == '__main__':
    p=Process(target=test)
    p.start()
    print('========main')
    time.sleep(3)
    print(x)

operation result:


How the parent process waits for the child process to end - join()

from multiprocessing import Process
import time,random

def test(n):
    print('%s is running'%n)
    time.sleep (random.randint (1,4))
    print('%s child process has ended'%n)

if __name__ == '__main__':
    start_time=time.time()
    p_l=[]
    for i in range(5):
        p=Process(target=test,args=(i,))
        p_l.append(p)
        p.start()
    for p in p_l:
        p.join()
    # p.join()#Let the parent process wait in place
    print('Main ==== Running time: %s'%(time.time()-start_time))

operation result:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324858384&siteId=291194637