开发者社区 问答 正文

如何陷入for循环?

你好,我有一个问题,我需要等待在一个for循环一段时间,直到一个布尔变量的值改变。我有意要在循环中等待。示例代码

check = True  

def change_check_value():
    global check
    ###
    after a while check changes to true
    ###

change_check_vale()  #running on a different thread

for i in range(0,10):
    print(i)
    check = False
    ## wait till check becomes true and continue the for loop

我想在for循环中等待,直到检查再次变为true ..我尝试了while循环,但我无法实现功能。时间不能用,因为我不知道要等多长时间。有人能帮我吗? 谢谢。 问题来源StackOverflow 地址:/questions/59385934/how-to-get-stuck-in-a-for-loop

展开
收起
kun坤 2019-12-25 22:12:08 497 分享 版权
1 条回答
写回答
取消 提交回答
  • 您可以使用事件对象,它可以在线程和异步包下找到。 事件对象有一个wait()方法,当调用它时,代码将不会继续,直到事件设置为true。 一旦事件被设置为True,代码将立即继续。 asyncio示例(源):

    async def waiter(event):
        print('waiting for it ...')
        await event.wait()
        print('... got it!')
    
    async def main():
        # Create an Event object.
        event = asyncio.Event()
    
        # Spawn a Task to wait until 'event' is set.
        waiter_task = asyncio.create_task(waiter(event))
    
        # Sleep for 1 second and set the event.
        await asyncio.sleep(1)
        event.set()
    
        # Wait until the waiter task is finished.
        await waiter_task
    
    asyncio.run(main())
    

    线程示例(源):

    import threading
    import time
    import logging
    
    logging.basicConfig(level=logging.DEBUG,
                        format='(%(threadName)-9s) %(message)s',)
    
    def wait_for_event(e):
        logging.debug('wait_for_event starting')
        event_is_set = e.wait()
        logging.debug('event set: %s', event_is_set)
    
    def wait_for_event_timeout(e, t):
        while not e.isSet():
            logging.debug('wait_for_event_timeout starting')
            event_is_set = e.wait(t)
            logging.debug('event set: %s', event_is_set)
            if event_is_set:
                logging.debug('processing event')
            else:
                logging.debug('doing other things')
    
    if __name__ == '__main__':
        e = threading.Event()
        t1 = threading.Thread(name='blocking', 
                          target=wait_for_event,
                          args=(e,))
        t1.start()
    
        t2 = threading.Thread(name='non-blocking', 
                          target=wait_for_event_timeout, 
                          args=(e, 2))
        t2.start()
    
        logging.debug('Waiting before calling Event.set()')
        time.sleep(3)
        e.set()
        logging.debug('Event is set')
    
    2019-12-25 22:12:16
    赞同 展开评论
问答地址: