Python线程:等待线程停止然后执行功能

问题描述 投票:0回答:1

我正在尝试在线程完成后运行一个函数,但未调用该函数。代码结构:

class():

    def functiontocall()
        do something with A

    def watchthread():
        thread()
        functiontocall()
        # since this function depends on variable A, it throws an error.
        # I tried: if thread.join == True: functiontocall but this did not call the function.

    def thread():
        def run():
            pythoncom.CoInitialize()
            --- do stuff --
            return A
        self.thread = threading.Thread(target=run)
        self.thread.start()

thread.join应该告诉我线程何时完成,但是由于某些原因,我仍然无法通过functiontocall进行操作。

一般来说,这是组织线程的一种坏方法吗?

python python-multithreading
1个回答
0
投票

因为您正在使用线程,所以一旦线程启动,Python将移至下一件事,除非您要求,否则它不会等待线程完成。

[使用您的代码,如果要在继续运行之前等待线程函数完成,那么听起来好像不需要线程,正常的函数将运行,完成,然后Python将移至正在运行的functiontocall()] >

[如果有原因需要使用示例中未涉及的线程,那么我建议使用thread.join()

threads = []  # list to hold threads if you have more than one
t = threading.Thread(target=run)
threads.append(t)

for thread in threads:  # wait for all threads to finish
    thread.join() 

functiontocall()  # will only run after all threads are done

再次,我建议重新检查线程是否是您需要在此处使用的,因为它似乎并不明显。

© www.soinside.com 2019 - 2024. All rights reserved.