进程

一,用函数方法写多进程
from multiprocessing import Process
import os
import time
def info(titile):
    print(title)
    print('module name',__name__)
    print('prarent process:',os.getppid)
    print('process id:',os.getpid)
def f(name):
    info('\033[31;1mfunction f\033[0m')
    print('hello',name)    
            
if __name__=='__main__':#此代码必须要写,否则要报错
    info('\033[32;1mmain process line\033[0m')
    time.sleep(1)
    p = Process(target=info,argv=('bob',))
    p.start()
    p.join()
用函数方法写进程

 1.os.getpid(0#获取进程id

2.os.getppid()#获取父进程id

3.进程之间的关系:

  子进程的父进程是主进程,主进程的父进程是运行的进程id,每一进程都有一个父进程,最终会归结到一个根进程。

from mutiprocessing import Process
import time
import os
class Myprocess(Process):
    def __init__(self,name):
        super(Myprocess,self).__init__()
        self.name=name
    def run():
        time.sleep(1)
        print('hello',self.name,time.ctime())
if __name__=='__main__':
    p_list=[]
    for i in range(3):
        p=Myprocess('alex')
        p.start()
        p_list.append(p)
    for p in p_list:
    
        p.join(0
    print('end')

 三。进程间通信

两种方法:queue,与pipe

from multiprocess import Process,Queue
def f(q,n):
    q.put([42,n,'hello']) #要将队列当作形参传入   
if __name__=='__main__':
    q = Queue()
    p_list=[]
    for i in range(3):
        p = Proces(target=f,argv=(q,i))
        p_list.append(p)
        p.start()
    print(q.get())
    
    
    print(q.get())
    print(q.get())
    for i in range(3):
        i.join()
from multiprocess import Process,Pipe
def f(conn):#conn为管道的一端
    conn.send([42,None,'hello'])
    conn.close()
if __name__=='__main__':
    parent_pipe,childe_pipe=Pipe()
    p = Process(targe=f,argv=(childe_pipe))    
    p.start()
    print(parent_pipe.recv())
    p.join()

四.Manager创建的东西可以直接通信

from multiprocess import Process,Manager
def f(d,l,i):
    d[i]=i
    
    l.append(i)
    d['good']='day'
if __name__=='__main__':
    with Manager() as manager:
    d=manager.dict()
    l=manager.list()
    p_list=[]
    for i in range(10):
        p = Process(target=f,argv=(d,l,i))
        p.start()
        p_list.append()
    for i in p_list():
        i.join()

 

posted on 2020-01-30 16:40  居一雪  阅读(102)  评论(0编辑  收藏  举报

导航