Multiple processes in concurrent programming

multi-process

Today we mainly talked about the creation of the process:

The creation of processes is divided into four types: among them, opening child processes in the process is the focus of our discussion.

   1. System initialization (use the ps command to view the process in linux, use the task manager in windows, the foreground process is responsible for interacting with the user, the process running in the background has nothing to do with the user, and the process that 
runs in the background and only wakes up when needed is called daemons such as email, web pages, news, print)   
2. A process starts a subprocess during the running process (such as nginx opens multiple processes, os.fork, subprocess.Popen, etc.)   3. The user's interactive request, and create a new process (such as the user double-click Baofengyingyin)   4. Initialization of a batch job (applies only to mainframe batch systems)

  Either way, a new process is created by an existing process executing a system call to create a process:

  1. In UNIX the system call is: fork, which creates an exact copy of the parent process with the same storage image, the same environment strings, and the same open files (in the shell interpreter process, execute A single command will create a child process)

  2. In windows, the system call is: CreateProcess, CreateProcess not only handles the creation of the process, but also is responsible for loading the correct program into the new process.

Two There are two ways to start the process:

Method 1 to open a subprocess:
 from multiprocessing import Process
 import time
 def run(name):
    time.sleep(2)
    print('%s is running'%name)
if __name__ == '__main__':
    t=Process(target=run,args=('feng',))
    t=Process(target=func,kwargs={'name':'feng'})#args is the same as kwargs but the form is different.
    t.start()###### Send 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, and initialize the data of the child process.
    The result of print ( ' zhu ' .center(50, ' * ' ))           
is:

************************zhu************************
feng is running

The operation of the whole program is actually to define a function run first, then run the main program, and create a sub-process in the process of running the main program. The sub-process is created by the operating system. The time required to create a subroutine is much longer than running a line of code, so first print out ************************zhu******** ****************, then the child process starts to run, output feng is running

方式二:
from multiprocessing import Process
import  time
class MyProcess(Process):
    def __init__(self,name):
        super().__init__()
        self.name=name
    def run(self):
        time.sleep(2)
        print('%s is running'%self.name)
if __name__ == '__main__': 
t=MyProcess('feng')
t.start()
print('zhu'.center(50,'='))
The result is:

========================zhu==========================
feng is running

To run the entire program, first define a class.

 

The following is the relationship between our child process and the parent process:

    1 Processes are isolated from each other in memory:

from multiprocessing import Process
import time
x=1000
def run(name):
    global x
    x=0
    time.sleep(2)
    print('%s is running'%name,x)
if __name__ == '__main__':
    t=Process(target=run,args=('feng',))
    t.start() #Here the child process starts, in fact, it calls the run in the parent process, executes, 
    time.sleep(5 )
     print (x) 
The result of the operation:

feng is running 0
1000

x=1000 is determined at the definition stage, so the x of the main process will not change with the change in the child process, and if we print x in the child process, it will be the changed value.

Through this process, we can see that the memory space of the child process and the parent process is independent. That is, changes in the child process will not affect the parent process. The parent process does not execute the code inside the run.

     2 Join usage: It is to let the parent process wait for the child process to finish running before running.

The usage of jion we talked about:
 from multiprocessing import Process
 import time
x=1000
def task():
    time.sleep(3)
    global  x
    x = 0
     print ( ' Son is over ' ,x)

if __name__ == '__main__':
    print(x)
    p=Process(target=task,)
    p.start()
    p.join()     # #Let the father wait in place. The parent process will not continue to run until the child process finishes running. 
    print (x)
 #The result of the operation is: 
'''
1000
Son ended 0
1000'''

  3  子进程实现并发:

# from multiprocessing import Process
# import time
#
# def task(n):
#     print('%s is running'%n)
# if __name__ == '__main__':
#     for i in range(1,4):
#         p=Process(target=task,args=(i,))
#         p.start()
#
#      print('Main'.center(20,'=')) 
# # The output is: 
# ''' 
# =========Main========== 
# 3 is running 
# 1 is running 
# 2 is running'''#Why the output result is out of order: that's because start just sends a request to the operating system to create a child process, then after the child process is created, why run it 
# This is entirely caused by The operating system controls it.

   4 join and concurrency:

Method 1: Compare the low method 
from
multiprocessing import Process import time def task(n): print('%s is running'%n) time.sleep(3) if __name__ == '__main__': p1=Process(target=task,args=(1,)) p2 = Process(target=task, args=(2,)) p3 = Process(target=task, args=(3,)) p1.start() p2.start() p3.start() p1.join() p2.join() p3.join() print ( ' main ' ) #The result of the operation is: ''' 2 is running 1 is running 3 is running
Method 2: Use a loop:
from multiprocessing import Process
import time
def task(n):
    print('%s is running'%n)
    time.sleep(3)

if __name__ == '__main__':
#     start_time=time.time()
# p_list=[]
# for i in range(1,4):
# p=Process(target=task,args=(i,))
# p_list.append(p)
# p.start()
# for p in p_list:
# p.join()
# print('主',time.time()-start_time)
Running result: 
# '''
# 2 is running
# 1 is running
# 3 is running
# main 2.1594531536102295
# '''

   5 View the process id or pid

# from multiprocessing import Process
# import time,random
# import os
#
# def task():
#     time.sleep(2)
#     print('me:%s,father:%s'%(os.getpid(),os.getppid()))
# if __name__ == '__main__':
#     p2=Process(target=task,)
#     p2.start()
#     # p2.join()
#
#     print(p2.name,p2.pid)
#     print('主',os.getppid())
print('main', os.getpid())# The result of this output is the same as the father of the child process. 
print('main', os.getppid())#And the result of this output is the pid of pycha.

# # The result of the operation is: # ''' # Process-1 8200 #main 3428 # me:8200,father:4940'''

Zombie process: The child process is dead, the parent process is still there (the parent process creates a lot of child processes, resulting in a large number of pids being occupied), the zombie process is harmful.

Orphan process: The parent process ends first, the child process is managed by init, and the orphan process is harmless.

 

Guess you like

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