Advanced Process 27

Between processes running order

import time,os
from multiprocessing import Process
def func(args1,args2):
    print(args1,args2)
    print(1234)
    time.sleep(1)
    print(654323)
if __name__ == '__main__':
    p = Process(target=func,args=('canshu1','canshu2'))# 注册一个进程
    #p是一个进程对象,还没有启动,通过start()来启动
    p.start()
    print('1234567') #此时这个 print与p进程是同时进行的,不知道他俩谁快谁满。
    print('父进程:',os.getpid())#查看当前进程的进程号 getpid意思是get parent id
    print('父进程的父进程:',os.getppid())#查看当前进程的父进程 getppid意思是get parent process id

Output: both an application running through the asynchronous operation mode.
Here Insert Picture Description

Process life cycle

  • Primary process
  • Child process
  • It opened a sub-process of the main process:
    1. The main process your own code if a long wait love their end code execution
    2. child process execution for a long time, the main process will be completed after the main process code execution, waiting for the child process is finished Thereafter, the main process until the end.

join method process

import time
from multiprocessing import Process
def func(args1,args2):
    print('*'* args1)
    time.sleep(3)
    print('-' *args2)
if __name__ == '__main__':
    p = Process(target = func,args=(4,4))
    p.start()
    p.join()    #感知一个子进程的结束,将异步的程序改为同步
    print('=======================================:打印完了')

Output:
Here Insert Picture Description
custom class needs to inherit the Process class, must implement a run method, run method is the code that is executed in the child process.

import os
from multiprocessing import Process
class Myprocess(Process):
    def run(self):
        print(os.getpid)
if __name__ == '__main__':
    print('主:',os.getpid())
    p1 = Myprocess()
    p1.start()
    p2 = Myprocess()
    p2.start()

Output:
Here Insert Picture Description

Pass parameters

Special Note: Be sure to implement the run method, since the start of the process method, depending on the run methods in the class, so be sure to implement the run method in the class.

import os
from multiprocessing import Process
class Myprocess(Process):
    def __init__(self,arg1,arg2):
        super().__init__() #使用父类的init方法
        self.arg1 = arg1
        self.arg2 = arg2
    def run(self):
        print(self.arg1,self.arg2)
        print(os.getpid)
if __name__ == '__main__':
    print('主:',os.getpid())
    p1 = Myprocess(3,2)
    p1.start()
    p2 = Myprocess(6,7)
    p2.start()

Data between multiple processes to isolate the problem

Between processes and process data are completely isolated.

import os
from multiprocessing import Process
def func():
    global n
    n = 0
    print('pid:%s'%os.getpid(),n)
if __name__ == '__main__':
    n = 100
    p = Process(target=func)
    p.start()
    p.join()
    print(os.getpid(),n)

Output:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_43265998/article/details/89918417