python Process creation process

The python multiprocessing module provides the Process class
There are two ways to create multithreads using the Process class:

  1. Directly create an instance object of the Process class to create a new Process
  2. You can create instance objects or new processes by inheriting subclasses of the Process class. Subclasses that inherit from the Process class need to override the run() method of the parent class

Common properties and methods of Process class

  • pid returns the ID number of the process. Most operating systems provide a unique ID number for each process
  • Name can rename the process or get the process name
  • Daemon can set the new process as a daemon by setting this property to true
  • is_alive() determines whether the current process is still alive
  • Join daemon, other processes must wait until the process that calls the join() method completes execution before proceeding
  • start() starts the newly created process
  • run() is the second way to create a process. The inherited class needs to rewrite the method, which contains the code to be executed by the new process.

Create a Process through the Process class

To create an instantiated object using the Process class is essentially to call the constructor of the class to create a new Process. The format of Process construction method is as follows:

def __init__(self,group=None,target=None,name=None,args=(),kwargs={})
  • target: Specifies the execution task for the new process. It is a function
  • Name sets the name for the new process
  • args passes a non keyword parameter for the operation specified by the target parameter
  • kwargs specifies parameters for the target parameter and passes keyword parameters
from multiprocessing import Process
import os
print("Current process ID: ",os.getpid())
# Define a function to be used as the target parameter of the new process
def action(name,*add):
    print(name)
    for arc in add:
        print("%s --Child process currently created%d" % (arc,os.getpid()))
if __name__=='__main__':
    #Defines the parameters passed in for the process method
    my_tuple = ("python",\
                "shell",\
                "java")
    #Create a child process and execute the action() function
    my_process = Process(target = action, args = ("my_process process",*my_tuple))
    #Start child process
    my_process.start()
    #The main process executes the function
    action("Main process",*my_tuple)

result
 Current process ID:  8668
 Main process
python --Currently created subprocess 8668
shell --Currently created subprocess 8668
java --Currently created subprocess 8668
 Current process ID:  15016
my_process process
python --Currently created child process 15016
shell --Currently created child process 15016
java --Currently created child process 15016

It should be noted that when creating and starting a subprocess through multiprocessing.Process, the program must first judge if name = = 'main':, otherwise running the program will cause an exception.

There are two processes in this program, the main process and the new process we created. The main process will execute the whole program, while the sub process will not execute the program contained in if name = = 'main', but first execute all executable programs other than this judgment statement, and then execute the tasks we assigned it to execute

Create a Process through the Process inheritance class

When creating a Process subclass, you need to override the run() method with the subclass content.

from multiprocessing import Process
import os
print("Current process ID: ",os.getpid())
# Define a function for the main process to call
def action(name,*add):
    print(name)
    for arc in add:
        print("%s --Current process%d" % (arc,os.getpid()))
#Customize a process class
class My_Process(Process):
    def __init__(self,name,*add):
        super().__init__()
        self.name = name
        self.add = add
    def run(self):
        print(self.name)
        for arc in self.add:
            print("%s --Current process%d" % (arc,os.getpid()))
if __name__=='__main__':
    #Defines the parameters passed in for the process method
    my_tuple = ("python",\
                "shell",\
                "java")
    my_process = My_Process("my_process process",*my_tuple)
    #Start child process
    my_process.start()
    #The main process executes the function
    action("Main process",*my_tuple)

result
 Current process ID:  6756
 Main process
python --Current process 6756
shell --Current process 6756
java --Current process 6756
 Current process ID:  8156
my_process process
python --Current process 8156
shell --Current process 8156
java --Current process 8156

It is recommended to use the first method to create a process, because this method is not only simple to program, but also the process directly wraps the target function and has a clearer logical structure.

Tags: Python Back-end

Posted on Fri, 03 Dec 2021 19:42:37 -0500 by bschultz