用于确定线程是否已完成的非阻塞方式?

时间:2016-08-16 14:22:34

标签: 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()

3 个答案:

答案 0 :(得分:1)

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

import threading
import time

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

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

    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
Something else
work done
Done

答案 1 :(得分:1)

executions = data['executions']
order_id = executions[0]['orderId']

OUT:

id

答案 2 :(得分:0)

import threading
dt = {}
threading.Thread(target=dt.update, kwargs=dict(out=123)).start()

while 'out' not in dt:
    print('out' in dt)
print(dt)