![](/img/trans.png)
[英]How to terminate “multiprocessing.Process” correctly when using “cv2.VideoCapture” (Python OpenCV)?
[英]How to correctly terminate multiprocessing.Process()?
我有一个需要以下列方式运行多个并行线程的代码:
def driver():
#Gets a UID and passes it to Run
run(uid)
def f1(a,b,c):
#Does Some thing : Trivial Example Below - These Operations might take long time
d=a+b+c
print(d)
def f2(a,b,c):
#Does Some thing : Trivial Example Below - These Operations might take long time
d=a+b*c
e=a+b/c
print(d,e)
现在,我有一个run()
方法可以并行运行这些。
from multiprocessing import Process
def run(uid):
#Get a,b,c on the basis of UID then call the following
thread_1=Process(target=f1, args=(a,b,c))
thread_2=Process(target=f2, args=(a,b,c))
thread_1.start()
thread_2.start()
thread_1.join()
thread_2.join()
代码的入口点是driver()
。 但是,我的代码在进行了一定数量的操作后卡住了,我猜这是由于内存问题。
我的问题是:如何在线程成功执行后正确终止它们? 执行后它们是否仍然驻留在内存中?
我运行这些线程的方式有什么问题吗?
使用线程池执行程序或线程库来更轻松地管理事情。
线程池执行器可以按如下方式使用。
def test(n):
print(n)
with ThreadPoolExecutor(max_workers=5) as executor:
for i in range(10):
executor.submit(test, args)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.