multiprocessing 是 python 中常用的多进程库,话不多说来看示例。
'''
@Time : 2021/8/26
@Author : Yanyuxiang
@Email : yanyuxiangtoday@163.com
@FileName: quick_start.py
@Software: PyCharm
'''
from multiprocessing import Process
import os
def info(title):
print('-' * 10)
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
for i in range(10 ** 6):
pass
print(f'{title} {os.getpid()} done')
def main():
p_list = []
for i in range(3):
p_list.append(Process(target=info, args=(i, )))
p_list[i].start()
for i in range(3):
p_list[i].join()
print('All process done.')
if __name__ == '__main__':
main()
>>> python3 quick_start.py
----------
1
module name: __mp_main__
parent process: 55175
process id: 55178
----------
0
module name: __mp_main__
parent process: 55175
process id: 55177
----------
2
module name: __mp_main__
parent process: 55175
process id: 55179
1 55178 done
0 55177 done
2 55179 done
All process done.
从输出上可以看出看出三个进程分别有各自的 process id ,同时有共同的 parent process id ,即他们由同一个父进程持有的三个子进程。
博主会持续更新一些人工智能领域的知识和实践、工作中遇到的问题和感悟、高效工作的方法和技巧,如果喜欢请关注、点赞、收藏支持
|