进程

天涯浪子 提交于 2020-03-25 19:06:15
#开启进程方式1 
from multiprocessing import Process
import time

def work(name):
    print("target %s is running" %name)
    time.sleep(2)
    print("target %s is done" %name)
if __name__=="__main__":
    p1=Process(target=work,args=("egon",))
    p2=Process(target=work,args=("alex",))
    p1.start()#向操作系统发送请求,开启进程
    p2.start()
    print("主进程")
'''
主进程
target egon is running
target alex is running
target alex is done
target egon is done
'''
#开启进程方式2
from multiprocessing import Process
import time
class MyProcess(Process):
    def __init__(self,name):
        super().__init__()
        self.name=name
    def run(self):
        print("target %s is running" %self.name)
        time.sleep(2)
        print("target %s is done" %self.name)
if __name__=="__main__":
    p1=MyProcess("egon")
    p2=MyProcess("alex")
    p1.start()#向操作系统发送请求,开启进程
    p2.start()
    print("主进程")
'''
主进程
target alex is running
target egon is running
target alex is done
target egon is done
'''
#join方法[并行]:主进程等待子进程运行
from multiprocessing import Process
import time

def work(name):
    print("target %s is running" %name)
    time.sleep(2)
    print("target %s is done" %name)
if __name__=="__main__":
    p1=Process(target=work,args=("egon",))
    p2=Process(target=work,args=("alex",))
#     p1.start()#向操作系统发送请求,开启进程
#     p2.start()
#     p1.join()#主进程等待p1结束
#     p2.join()
    p_list=[p1,p2]
    for p in p_list:
        p.start()
    for p in p_list:
        p.join()        
    print("主进程") #等待时间为程序运行时间最长的那个程序
'''
target egon is running
target alex is running
target alex is done
target egon is done
主进程
'''
#join方法[串行]:主进程等待子进程运行
from multiprocessing import Process
import time
#并发,在同一个终端打印
def work(name):
    print("target %s is running" %name)
    time.sleep(2)
    print("target %s is done" %name)
if __name__=="__main__":
    p1=Process(target=work,args=("egon",))
    p2=Process(target=work,args=("alex",))
#     p1.start()#向操作系统发送请求,开启进程
#     p2.start()
#     p1.join()#主进程等待p1结束
#     p2.join()
    p_list=[p1,p2]
    for p in p_list:
        p.start()
        p.join()
           
    print("主进程") #等待时间为程序运行时间最长的那个程序
'''
target egon is running
target egon is done
target alex is running
target alex is done
主进程
'''
#pid,ppid,name
from multiprocessing import Process
import time
import os
#并发,在同一个终端打印
def work():
    
    print("parent:%s target %s is running" %(os.getppid(),os.getpid()))
    time.sleep(2)
    print("parent:%s target %s is done" %(os.getppid(),os.getpid()))
if __name__=="__main__":
    p1=Process(target=work,name="egon_process")
    p1.start()#向操作系统发送请求,开启进程
    print("进程name: ",p1.name)
    print("pycharm的Pid:",os.getppid())#pycharm
    print("主进程Pid:",os.getpid())
    print("子进程p1的pid:",p1.pid)#10666
'''
进程name:  egon_process
pycharm的Pid: 140659
主进程Pid: 10385
子进程p1的pid: 10727
parent:10385 target 10727 is running
parent:10385 target 10727 is done

'''

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!