python 如何陷入for循环?

00jrzges  于 2023-06-20  发布在  Python
关注(0)|答案(3)|浏览(64)

我有一个问题,我需要在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循环,但我无法实现功能。time.sleep()无法使用,因为我不确定要等待多少时间。

lnlaulya

lnlaulya1#

您可以使用 Event 对象,它可以在 threadingasyncio 包下找到。
事件对象有一个 wait() 方法,当调用它时,代码将不会继续,直到Event设置为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')
xggvc2p6

xggvc2p62#

尝试使用这篇文章中提到的方法: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()

希望能帮上忙。

j0pj023g

j0pj023g3#

这可以用一种非常简单的方式来实现:

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

相关问题