# -*- coding: utf-8 -*-
"""
@File : 20200318_摄像头多进程流传输.py
@Time : 2020/3/18 14:58
@Author : Dontla
@Email : [email protected]
@Software: PyCharm
"""
import datetime
from multiprocessing import Pool
import time
def test(p):
time.sleep(1)
print(datetime.datetime.now())
return p
if __name__ == "__main__":
pool = Pool(processes=2)
result = []
for i in range(10):
'''
for循环执行流程:
(1)添加子进程到pool,并将这个对象(子进程)添加到result这个列表中。(此时子进程并没有运行)
(2)执行子进程(同时执行10个)
'''
# Dontla 20200319 apply_async()是啥意思?
result.append(pool.apply_async(test, args=(i,))) # 维持执行的进程总数为10,当一个进程执行完后添加新进程.
pool.close()
# Dontla 20200319 阻塞主程序等待子进程执行完成
pool.join()
'''
遍历result列表,取出子进程对象,访问get()方法,获取返回值。(此时所有子进程已执行完毕)
'''
for i in result:
print(i.get())
结果:
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/20200318_摄像头多进程流传输.py
2020-03-24 08:56:15.331693
2020-03-24 08:56:15.331693
2020-03-24 08:56:16.332564
2020-03-24 08:56:16.332564
2020-03-24 08:56:17.333423
2020-03-24 08:56:17.333423
2020-03-24 08:56:18.334177
2020-03-24 08:56:18.334177
2020-03-24 08:56:19.334215
2020-03-24 08:56:19.334215
0
1
2
3
4
5
6
7
8
9
Process finished with exit code 0
# -*- coding: utf-8 -*-
"""
@File : test4.py
@Time : 2020/3/24 8:40
@Author : Dontla
@Email : [email protected]
@Software: PyCharm
"""
# -*- coding: utf-8 -*-
"""
@File : 20200318_摄像头多进程流传输.py
@Time : 2020/3/18 14:58
@Author : Dontla
@Email : [email protected]
@Software: PyCharm
"""
import datetime
from multiprocessing import Pool
import time
def test(p):
time.sleep(1)
print(datetime.datetime.now())
return p
if __name__ == "__main__":
pool = Pool(processes=2)
result = []
for i in range(10):
'''
for循环执行流程:
(1)添加子进程到pool,并将这个对象(子进程)添加到result这个列表中。(此时子进程并没有运行)
(2)执行子进程(同时执行10个)
'''
# Dontla 20200319 apply_async()是啥意思?
# result.append(pool.apply_async(test, args=(i,))) # 维持执行的进程总数为10,当一个进程执行完后添加新进程.
# get()是一个阻塞线程的方法?是的,要获取函数结果,必须阻塞
# print(pool.apply_async(test, args=(i,)).get())
pool.apply_async(test, args=(i,)).get()
# pool.close()
# Dontla 20200319 阻塞主程序等待子进程执行完成
# pool.join()
'''
遍历result列表,取出子进程对象,访问get()方法,获取返回值。(此时所有子进程已执行完毕)
'''
# for i in result:
# print(i.get())
print('over')
D:\20191031_tensorflow_yolov3\python\python.exe C:/Users/SIQI/Desktop/test_multiprocessing/test4.py
2020-03-24 09:05:54.157505
2020-03-24 09:05:55.157542
2020-03-24 09:05:56.157578
2020-03-24 09:05:57.157614
2020-03-24 09:05:58.158199
2020-03-24 09:05:59.158941
2020-03-24 09:06:00.159096
2020-03-24 09:06:01.159715
2020-03-24 09:06:02.160607
2020-03-24 09:06:03.161478
over
Process finished with exit code 0
参考文章1:python中使用多进程multiprocessing并获取子进程的返回值
参考文章2:Python对进程Multiprocessing子进程返回值