I started learning asynchronous development in Python 3 and faced the following dilemma:
Suppose I have tasks, and inside I check that if this task is completed for a long time, then I “postpone” it (transferring control to the next corute in the event loop):
import asyncio import time async def calculate(value): if value > 10000: await asyncio.sleep(0.0001) data = value ** value print('Calculated {}'.format(value)) return data async def main(): task_1 = calculate(98230) task_2 = calculate(16780) task_3 = calculate(656) task_4 = calculate(1078) tasks_list = [task_1, task_2, task_3, task_4] finished, unfinished = await asyncio.wait(tasks_list, loop=loop, return_when=asyncio.ALL_COMPLETED) for unfinished_task in unfinished: unfinished_task.cancel() return finished if __name__ == '__main__': start = time.time() loop = asyncio.get_event_loop() result = loop.run_until_complete(main()) loop.close() print('Exec time: ' + str(time.time() - start)) And accordingly, the question is how can I check whether other tasks are “ready” to start calculations for the current one, for example:
async def calculate(value): if value > 10000: while not loop.other_tasks_done(): await asyncio.sleep(0.0001) data = value ** value print('Calculated {}'.format(value)) return data
await asyncio.sleep(0)also transfers control to other corintines - andreymal