进程创建的两个方式 进程pid 验证进程之间的空间隔离 进程对象join方法 进程的其他参数 守护进程

进程创建的两种方式

第一种方法:

from multiprocessing import Process
import time


def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")


if __name__ == '__main__':
    # 在windows环境下, 开启进程必须在__name__ == '__main__'下面
    p = Process(target=task, args=("常鑫",)) # 创建一个进程对象
    p.start() # 只是向操作系统发出一个开辟子进程的信号,然后就执行下一行了
    # 这个信号操作系统接收到之后, 会从内存中开辟一个子进程空间, 然后再将主进程所有数据copy加载到子进程, 然后再调用CPU去执行
    # 开辟子进程开销是很大的
    print("==主开始")
    
"""
==主开始
常鑫 is running
常鑫 is gone
"""

第二种方法:

from multiprocessing import Process
import time

class MyProcess(Process):

    def __init__(self, name):
        super().__init__()
        self.name = name

    def run(self):
        print(f"{self.name} is running")
        time.sleep(2)
        print(f"{self.name} is gone")

if __name__ == '__main__':
    p = MyProcess('常鑫')
    p.start()
    print('===主程序')
    
"""
===主程序
常鑫 is running
常鑫 is gone
"""

简单应用

from multiprocessing import Process
import time


def task(name):
    print(f"{name} is running")
    time.sleep(1)
    print(f"{name} is gone")


def task1(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")


def task2(name):
    print(f"{name} is running")
    time.sleep(3)
    print(f"{name} is gone")

    
    
# 一个进程串行的执行三个任务
if __name__ == '__main__':
    start_time = time.time()
    task("常鑫")
    task1("李远点业")
    task2("海狗")
    print(f"结束时间{time.time() - start_time}")
    
"""
常鑫 is running
常鑫 is gone
李远点业 is running
李远点业 is gone
海狗 is running
海狗 is gone
结束时间6.001969337463379
"""

# 三个进程 并发或者并行的执行三个任务
if __name__ == '__main__':
    p1 = Process(target=task, args=("常鑫",))
    p2 = Process(target=task1, args=("李远点业",))
    p3 = Process(target=task2, args=("海狗",))
    start_time = time.time()
    p1.start()
    p2.start()
    p3.start()
    time.sleep(5)
    print(f"结束时间{time.time() - start_time}")
    
"""
常鑫 is running
李远点业 is running
海狗 is running
常鑫 is gone
李远点业 is gone
海狗 is gone
结束时间5.026661396026611
"""

进程pid

获取进程pid

import os
import time
print(f'子进程:{os.getpid()}')
print(f'主进程:{os.getppid()}')
time.sleep(50)

# 第一次执行
"""
子进程:139000
主进程:109036
"""

# 第二次执行
"""
子进程:136820
主进程:109036
"""

# 第三次执行
"""
子进程:139916
主进程:109036
"""
from multiprocessing import Process
import os

def task(name):
    print(f"子进程{os.getpid()}")
    print(f"主进程{os.getppid()}")

if __name__ == '__main__':
    p = Process(target=task, args=("常鑫",))
    p.start()
    print(f"===={os.getpid()}")
    
"""
====142800
子进程143244
主进程142800
"""
# 创建的进程的主进程就是 本模块此进程

验证进程之间的空间隔离

from multiprocessing import Process
import time
name = '太白'

def task():
    global name
    name = "刚子sb"
    print(f"子进程:{name}")

if __name__ == '__main__':
    p = Process(target=task)
    p.start()
    time.sleep(3)
    print(f"主:{name}")
"""
子进程:刚子sb
主:太白
"""
# 子进程的name变量即使有global也没有重新赋值, 因为进程之间的空间隔离

lst = ["丽丽", ]

from multiprocessing import Process
import time

def task():
    lst.append('怼姐')
    print(f"子进程{lst}")

if __name__ == '__main__':
    p = Process(target=task)
    p.start()
    time.sleep(3)
    print(f"主:{lst}")
"""
子进程['丽丽', '怼姐']
主:['丽丽']
"""
# 即使是列表也有空间隔离

进程对象join方法

单个子进程使用join

join让主进程等待子进程结束之后, 在执行主进程

from multiprocessing import Process
import time

def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")

if __name__ == '__main__':
    p = Process(target=task, args=("常鑫", ))
    p.start()
    p.join()
    print("==主进程")
    
"""
常鑫 is running
常鑫 is gone
==主进程
"""

多个子进程使用join

验证一:

from multiprocessing import Process
import time

def task(name,sec):
    print(f"{name} is running")
    time.sleep(sec)
    print(f"{name} is gone")

if __name__ == '__main__':
    start_time = time.time()
    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(f"==主进程{time.time() - start_time}")
    
"""
常鑫 is running
李业 is running
海狗 is running
常鑫 is gone
李业 is gone
海狗 is gone
==主进程:4.285647392272949
"""

验证2:

from multiprocessing import Process
import time

def task(name,sec):
    print(f"{name} is running")
    time.sleep(sec)
    print(f"{name} is gone")

if __name__ == '__main__':
    start_time = time.time()
    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()
    print(f"==主进程1:{time.time() - start_time}")
    p2.join()
    print(f"==主进程2:{time.time() - start_time}")
    p3.join()
    print(f"==主进程3:{time.time() - start_time}")
    
"""
常鑫 is running
李业 is running
海狗 is running
常鑫 is gone
==主进程1:2.2231969833374023
李业 is gone
==主进程2:3.232954502105713
海狗 is gone
==主进程3:4.242786645889282
"""

# start同时开启三个进程, 同时运行
# join就是阻塞

优化验证2:

from multiprocessing import Process
import time


def task(sec):
    print(f"子进程 is running")
    time.sleep(sec)
    print(f"子进程 is gone")


if __name__ == '__main__':
    start_time = time.time()
    l1 = []
    for i in range(1, 4):
        p = Process(target=task, args=(i,))
        l1.append(p)
        p.start()
    for i in l1:
        i.join()
    print(f"==主进程{time.time() - start_time})")
    
"""
子进程 is running
子进程 is running
子进程 is running
子进程 is gone
子进程 is gone
子进程 is gone
==主进程4.1986918449401855)
"""
# join就是阻塞, 主进程有join, 主进程下面的代码一律不执行, 直到进程执行完毕之后再执行

进程的其他参数

terminate(杀死)

from multiprocessing import Process
import time

def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")

if __name__ == '__main__':
    p = Process(target=task, args=("常鑫", ), name="alex")
    p.start()
    p.terminate()
    print("==主进程")

"""
==主进程
"""
# 子进程刚发出信号就杀死

from multiprocessing import Process
import time

def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")

if __name__ == '__main__':
    p = Process(target=task, args=("常鑫", ), name="alex")
    p.start()
    time.sleep(1)
    p.terminate()
    print("==主进程")

"""
常鑫 is running
==主进程
"""
# 睡了一秒所以子进程start了


is_alive(判断子进程是否存活)

from multiprocessing import Process
import time

def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")

if __name__ == '__main__':
    p = Process(target=task, args=("常鑫", ), name="alex")
    p.start()
    # p.terminate()
    # p.join()
    print(p.is_alive())
    print("==主进程")
    
"""
True
==主进程
常鑫 is running
常鑫 is gone
"""

# terminate 和 join 都会使进程结束, 所以有terminate 和 join 就会返回 False

守护进程

子进程守护着主进程, 只要主进程结束, 子进程跟着就结束

from multiprocessing import Process
import time

def task(name):
    print(f"{name} is running")
    time.sleep(2)
    print(f"{name} is gone")

if __name__ == '__main__':
    p = Process(target=task, args=("常鑫", ))
    p.daemon = True
    p.start()
    print("==主")
"""
常鑫 is running
常鑫 is gone
==主
"""
posted @ 2019-08-20 20:56  边城bei  阅读(138)  评论(0编辑  收藏  举报