简体   繁体   English

python3中,子线程满足某些条件时如何暂停和唤醒主线程?

[英]In python3, how to pause and wake up the main thread when some conditions are satisfied by child threads?

In python3, what I want is to pause the main thread until some conditions are satisfied by the child threads.在python3中,我想要的是暂停主线程,直到子线程满足某些条件。 I know it can be achieved by while condition loop like this:我知道它可以通过这样的while condition循环来实现:

class myThread(Thread):
    def __init__(self):
        super(myThread, self).__init__()
        self.count=0

    def run():
        self.count+=1

# main loop
myThread().start()
myThread().start()

# wait until some condition are satisfied
while not conditionSatisfied():
    pass

# then do the things
do_staff()

However, I wonder if it can be achieved by some "smarter" operations in the main thread, just like the lock: acquire()/release()/notify()/notifyAll() .但是,我想知道它是否可以通过主线程中的一些“更智能”的操作来实现,就像锁一样: acquire()/release()/notify()/notifyAll() I have used them before but only in the child threads.我以前使用过它们,但只在子线程中使用过。 This time I wonder how to achieve it in the main thread.这次我想知道如何在主线程中实现它。

Does this work for you?这对你有用吗?

from threading import Thread, Condition
import time

count = 0
class Child(Thread):

    def __init__(self, condition):
        self.condition = condition
        super().__init__()

    def run(self):
        global count
        print('child running')
        while True:
            with condition:
                if count != 10:
                    count += 1
                    print(f'child incrementing count to {count}')
                else:
                    print('child notifying')
                    self.condition.notify()
                    return
            time.sleep(1)


if __name__ == '__main__':
    condition = Condition()
    child = Child(condition)
    child.start()
    print('main thread waiting on condition ... ')

    with condition:
        while count != 10:
            condition.wait()
    print('Main thread waking up ')
    child.join()

Output: Output:

child running
child incrementing count to 1
main thread waiting on condition ... 
child incrementing count to 2
child incrementing count to 3
child incrementing count to 4
child incrementing count to 5
child incrementing count to 6
child incrementing count to 7
child incrementing count to 8
child incrementing count to 9
child incrementing count to 10
child notifying
Main thread waking up 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM