【问题标题】:Running Multiple functions in the same Thread in a specific order以特定顺序在同一个线程中运行多个函数
【发布时间】:2020-05-21 09:06:58
【问题描述】:

我有三个函数使用 papermill 执行 3 个不同的 jupyter 笔记本,我希望第一个 (job1) 和第二个 (job2) 函数同时运行,最后一个函数 (job3) 仅在第一个函数 (job1) 运行时运行完成运行,没有任何错误。我不确定为第二个函数创建一个新线程或如何正确使用 join() 方法是否有意义。 我在 Windows 上运行,由于某种原因 concurrent.futures 和多处理不起作用,这就是我使用线程模块的原因。

def job1():

    return pm.execute_notebook('notebook1.ipynb',log_output=False)

def job2():

     return pm.execute_notebook('notebook2.ipynb',log_output=False)

def job3():

     return pm.execute_notebook('notebook3.ipynb',log_output=False)


t1 = threading.Thread(target = job1)
t2 = threading.Thread(target = job2)
t3 = threading.Thread(target = job3)


try:
   t1.start()
   t1.join()
   t2.start()

except:
   pass

finally:

   t3.start()

【问题讨论】:

    标签: python concurrency jupyter-notebook python-multithreading papermill


    【解决方案1】:

    我喜欢从可视化所需的流程开始,我理解它看起来像:

    这意味着 t1 和 t2 需要同时启动,然后你需要同时加入:

       t1.start() # <- Started 
       t2.start() # <- Started
       # t1 and t2 executing concurrently
    
       t1.join()
       t2.join()
       # wait for both to finish
    
       t3.start()
       t3.join()
    

    t1, t2 连接顺序并不重要,因为您的程序无论如何都必须等待运行时间最长的线程。如果 t1 先完成,它将在 t2 上阻塞,如果 t2 先完成,它仍然需要等待 t1,然后将在 t2.join() 上“无操作”。

    【讨论】:

    • 您好,谢谢您的回答,就一个问题,如果t1遇到错误无法成功运行怎么办?是否可以插入任何类型的异常子句,以便 t3 仅在 t1 成功时运行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2012-12-28
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多