【发布时间】:2020-04-11 06:07:04
【问题描述】:
这是我尝试在主项目中执行的示例程序,但主要思想是我使用 asyncio.create_task 创建了一个任务。当某些事件发生时,我想稍后在代码中暂停该任务。在此示例代码中,asyncio.create_task 启动 task_tic_tock 并打印“tic-tock”。稍后在代码中,当 other_task 的计数可被 3 整除时,它会获取锁并启动 task_tic_tock,参数为 False。我不确定锁是最好使用的东西,但我希望的行为是让它打印“In new count”和“print val is now false”,而不是“tic-”tock”。曾经锁定结束我希望它恢复打印“tic_tock”。
import asyncio
lock = asyncio.Lock()
def task_tic_tock(print_val):
if print_val:
print("tic-tock")
else:
print("Print val is now false")
async def start_tic_tock(print_val):
while True:
task_tic_tock(print_val)
await asyncio.sleep(1)
async def other_task():
count = 0
while True:
count = count + 1
if count % 3 == 0:
async with lock:
task_tic_tock(False)
new_count = 5
while new_count > 0:
print("In new count")
new_count = new_count - 1
await asyncio.sleep(1)
await asyncio.sleep(1)
print("Other task running")
await asyncio.sleep(1)
async def main():
print_val = asyncio.create_task(start_tic_tock(True))
await asyncio.gather(other_task(), print_val)
asyncio.run(main())
create_task 是如何工作的,是否可以在另一个任务正在进行时暂停它一段时间?任何帮助将不胜感激!
【问题讨论】:
标签: python-3.x async-await python-asyncio