【问题标题】:How to correctly terminate multiprocessing.Process()?如何正确终止 multiprocessing.Process()?
【发布时间】:2020-11-19 11:18:50
【问题描述】:

我的代码需要通过以下方式运行多个并行线程:

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()。 但是,我的代码在经过一定次数的操作后卡住了,我猜这是由于内存问题。

我的问题是:如何在线程成功执行后正确终止线程?执行后它们是否仍然驻留在内存中?

我运行这些线程的方式有什么问题吗?

【问题讨论】:

  • 现在编写代码时,您没有并行运行任何东西。 join() 是一个阻塞调用。您启动 thread_1(一个进程,而不是线程,但您当然可以随意命名变量),等待它完成,然后启动 thread_2 并等待它完成。您应该首先将两个 start 语句并排放置,并且只有在您同时启动它们之后才加入进程。但这并不能回答您的问题,只是对您的代码的观察。
  • 编辑了代码,所以 start() for each 被调用,然后 join() 被调用。

标签: python python-3.x multiprocessing python-multiprocessing


【解决方案1】:

使用 Threadpool 执行器或 Threading 库来更轻松地管理事情。

线程池执行器可以如下使用。

def test(n):
 print(n)
            
with ThreadPoolExecutor(max_workers=5) as executor:
  for i in range(10):
     executor.submit(test, args)

https://apscheduler.readthedocs.io/en/latest/userguide.html

【讨论】:

    猜你喜欢
    • 2018-06-21
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多