Skip to main content
 首页 » 编程设计

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

2024年10月17日12rubylouvre

我有以下代码:

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