python - 确定线程是否完成的非阻塞方式?

标签 python multithreading

我有以下代码:

import threading
import time

class TestWorker (threading.Thread):
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name

    def run(self):
        print "Starting " + self.name
        time.sleep(20)
        print "Exiting " + self.name
        # how do I let the calling thread know it's done?

class TestMain:
    def __init__(self):
        pass

    def do_work(self):
        thread = TestWorker(1, "Thread-1")
        thread.start()

    def do_something_else(self):
        print "Something else"

    def on_work_done(self):
        print "work done"

如何让主线程知道 TestWorker 已经完成(调用 on_work_done()),而不阻塞对 do_something_else() 的调用> 像 thread.join() 那样?

最佳答案

您可以为您的线程实例提供一个可选的回调函数,以便在它完成时调用。
请注意,我添加了一个 Lock 来防止并发打印(这会阻塞)。

print_lock = threading.Lock()  # Prevent threads from printing at same time.

class TestWorker(threading.Thread):
    def __init__(self, threadID, name, callback=lambda: None):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.callback = callback

    def run(self):
        with print_lock:
            print("Starting " + self.name)
        time.sleep(3)
        with print_lock:
            print("Exiting " + self.name)
        self.callback()

class TestMain:
    def __init__(self):
        self.work_done = False

    def do_work(self):
        thread = TestWorker(1, "Thread-1", self.on_work_done)
        thread.start()

    def do_something_else(self):
        with print_lock:
            print("Something else")

    def on_work_done(self):
        with print_lock:
            print("work done")
        self.work_done = True

main = TestMain()
main.do_work()
while not main.work_done:
    main.do_something_else()
    time.sleep(.5)  # do other stuff...

print('Done')

输出:

Starting Thread-1
Something else
Something else
Something else
Something else
Something else
Something else
Exiting Thread-1
work done
Done

关于python - 确定线程是否完成的非阻塞方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38977472/

相关文章:

c# - 如何在 C# .net 中每天早上执行一个方法

c++ - std::mutex 使用示例

python - 控制 Altair 区域的堆栈顺序

python - 在打印中多次使用相同的变量

python - 从列表 rethinkdb ~python 更新特定数据

c# - 多线程后台 worker 设计

java - Java join() 方法的问题

Python 和 Pandas - 按日期排序

python - 在 Windows 10 上无法识别 Conda 命令

java - volatile 引用是在线程之间传递 MotionEvents 的安全方式吗?