【问题标题】:How to get stuck in a for loop?如何陷入 for 循环?
【发布时间】:2020-04-10 15:31:11
【问题描述】:

您好,我有一个问题,我需要在 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 循环中等待,直到检查再次变为真。我尝试使用 while 循环,但无法实现该功能。 time.sleep() 无法使用,因为我不确定要等待多长时间。有人可以帮我弄这个吗?

谢谢。

【问题讨论】:

  • 您可以使用time.sleep,但您最终可能会等待比您真正需要的时间更长的时间。另一个选项是condition variable

标签: python multithreading for-loop while-loop wait


【解决方案1】:

尝试使用本文中提到的方法:Is there an easy way in Python to wait until certain condition is true?

import time

check = True

def wait_until():
  while true:
    if check == True: return


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
    wait_until()

希望对你有帮助。

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • 好的。感谢您的评论。
【解决方案2】:

您可以使用 Event 对象,它可以在 threadingasyncio 包下找到。

事件对象有一个 wait() 方法,调用它时代码不会继续,直到事件设置为真。 一旦事件被设置为True,代码将立即继续。

异步示例 (source):

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())

线程示例 (source):

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')

【讨论】:

    【解决方案3】:

    这可以通过一种非常简单的方式完成:

    from threading import Event, Thread
    
    event = Event()
    
    
    def wait_for_it(e):
        print('Waiting for something to happen.')
        e.wait()
        print('No longer waiting.')
        e.clear()
        print('It can happen again.')
    
    
    def make_it_happen(e):
        print('Making it happen.')
        e.set()
        print('It happened.')
    
    
    # create the threads
    threads = [Thread(target=wait_for_it, args=(event,)), Thread(target=make_it_happen, args=(event,))]
    
    # start them
    for thread in threads:
        thread.start()
    
    # make the main thread wait for the others to complete
    for thread in threads:
        thread.join()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多