线程等待 Python 直到函数执行完成而不使用 join() 方法

Thread wait in Python till function execution is done without using join() method

我有一个线程,我在其中传递了函数。我现在想等到函数执行完毕。我可以让它等到传递给线程的函数完全执行而不使用 join() 吗?

就像我有一个示例代码片段。

# Some code
.
def sampleFunc():
    # func code
    .
    .
    .
.
.
.
thread = threading.Thread(target=sampleFunc, arg=())
thread.start()

print('After thread')
.
.
.

我有这样的东西,我在 tkinter 中使用,但是 print() 在线程完全执行之前打印 'After Thread'。我想运行线程完全执行后的代码。如果我使用 join() 它将冻结 tkinter。有什么办法可以做到这一点。如果您有任何建议,我愿意接受。谢谢

如果您不想在 sampleFunc() 的末尾添加 print(),您可以执行以下操作之一。

1. Subclass the Thread() and call the sampleFunc() inside the run() method like this:

import threading

class MyThread (threading.Thread):
    def run (self):
        sampleFunc()
        print("Sample func done")

thread = MyThread()
thread.start()

2. If you need it to tell you when the thread is almost completely done, then override the internal bootstraping method. In this case you can continue using your variant of the Thread() as before.

import threading

class Thread (threading.Thread):
    def _bootstrap (self):
        # Note that this method is called __bootstrap() in Python 2.x
        try:
            threading.Thread._bootstrap(self)
        except:
            print("Thread ended with an exception")
            raise
        print("Thread ended properly")

thread = Thread(target=sampleFunc, args=())
thread.start()

Someone will probably tell me that above shouldn't be done and that all that could have been achieved within the run() method, but I'll still stick with this solution. It leaves you space to subclass this Thread() version and implement different run()s as well as giving the thread function using target argument of a constructor.