一、进程的创建
我们先来回忆下之前多线程的实现。
- import threading
- import time
-
- def test1():
- while True:
- print("1------")
- time.sleep(1)
-
- def test2():
- while True:
- print("https://cdn.jxasp.com:9143/image/2------")
- time.sleep(1)
-
- def main():
- t1 = threading.Thread(target=test1)
- t2 = threading.Thread(target=test2)
- t1.start()
- t2.start()
-
- if __name__ == "__main__":
- main()
再来看看多进程的实现。
- import multiprocessing
- import time
-
- def test1():
- while True:
- print("1------")
- time.sleep(1)
-
- def test2():
- while True:
- print("https://cdn.jxasp.com:9143/image/2------")
- time.sleep(1)
-
- def main():
- t1 = multiprocessing.Process(target=test1)
- t2 = multiprocessing.Process(target=test2)
- t1.start()
- t2.start()
-
- if __name__ == "__main__":
- main()
multiprocessing 模块就是跨平台版本的多进程模块,提供了一个 Process 类来代表一个进程对象,这个对象可以理解为是一个独立的进程,可以执行另外的事情。
创建子进程时,只需要传入一个执行函数和函数的参数,创建一个 Process 实例,用start()方法启动。
通过比较,会惊奇地发现,创建多线程和创建多进程,步骤几乎是一样的。
和使用 Thread 类创建多线程方法类似,使用 Process 类创建多进程也有以下 2 种方式:
- 直接创建 Process 类的实例对象,由此就可以创建一个新的进程;
- 通过继承 Process 类的子类,创建实例对象,也可以创建新的进程。注意,继承 Process 类的子类需重写父类的 run() 方法。
二、Process 语法结构
Process([group [, target [, name [, args [, kwargs]]]]])
- target:如果传递了函数的引用,可以认为这个子进程就执行这里的代码。
- args:给 target 指定的函数传递非关键字参数,以元组的方式传递。
- kwargs:给 target 指定的函数传递命名(关键字)参数。
- name:给进程设定一个名字,可以不设定。
- group:指定进程组,大多数情况下用不到。
Process 创建的实例对象的常用方法
- start():启动子进程实例(创建子进程)。
- is_alive():判断进程子进程是否还在活着。
- join([timeout]):是否等待子进程执行结束,或等待多少秒。
- terminate():不管任务是否完成,立即终止子进程。
- run():继承类中需要对该方法进行重写,该方法中包含的是新进程要执行的代码。
Process创建的实例对象的常用属性
- name:当前进程的别名,默认为Process-N,N为从1开始递增的整数。
- pid:当前进程的pid(进程号)。
- daemon:和守护线程类似,通过设置该属性为 True,可将新建进程设置为守护进程。
三、获取进程的pid
- from multiprocessing import Process
- import os
-
- def run_proc():
- """子进程要执行的代码"""
- # os.getpid获取当前进程的进程号
- print('子进程运行中,pid=%d...' % os.getpid())
- print('子进程将要结束...')
-
- if __name__ == '__main__':
- # os.getpid获取当前进程的进程号
- print('父进程pid: %d' % os.getpid())
- p = Process(target=run_proc)
- p.start()
运行结果:
- 父进程pid: 12740
- 子进程运行中,pid=11192...
- 子进程将要结束...
四、给子进程指定的函数传递参数
- from multiprocessing import Process
- import os
- from time import sleep
-
- def run_proc(name, age, **kwargs):
- for i in range(10):
- print('子进程运行中,name= %s,age=%d ,pid=%d...' % (name, age, os.getpid()))
- print(kwargs)
- sleep(0.2)
-
- if __name__ == '__main__':
- p = Process(target=run_proc, args=('test', 18), kwargs={"m": 20})
- p.start()
- # 1秒中之后,立即结束子进程
- sleep(1)
- p.terminate()
- p.join()
运行结果:
- 子进程运行中,name= test,age=18 ,pid=10024...
- {'m': 20}
- 子进程运行中,name= test,age=18 ,pid=10024...
- {'m': 20}
- 子进程运行中,name= test,age=18 ,pid=10024...
- {'m': 20}
- 子进程运行中,name= test,age=18 ,pid=10024...
- {'m': 20}
- 子进程运行中,name= test,age=18 ,pid=10024...
- {'m': 20}