Python 3.x 线程在Python中等待函数执行完成,而不使用join()方法

Python 3.x 线程在Python中等待函数执行完成,而不使用join()方法,python-3.x,python-multithreading,Python 3.x,Python Multithreading,我有一个线程,在其中我传递了函数。现在我想等待函数执行完毕。我是否可以让它等待传递给线程的函数完全执行,而不使用join() 就像我有一个示例代码片段一样 # Some code . def sampleFunc(): # func code . . . . . . thread = threading.Thread(target=sampleFunc, arg=()) thread.start() print('After thread') . . . 我在

我有一个线程,在其中我传递了函数。现在我想等待函数执行完毕。我是否可以让它等待传递给线程的函数完全执行,而不使用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.