Код: Выделить всё
import asyncio
import random
def first_execution(choice):
if choice==1:
print(f"First result {choice}")
return choice
else:
print(f"First result {0}")
return 0
async def check_first_execution(result_from_first):
# Computationally complex function which take a lot of time to compute
await asyncio.sleep(10)
print(f"First check of value {result_from_first} complete")
async def second_execution(result_from_first):
# Moderately complex computation
await asyncio.sleep(5)
print(f"Second result {result_from_first+1}")
return result_from_first+1
async def check_second_execution(result_from_second):
# Computationally complex function which take a lot of time to compute
await asyncio.sleep(10)
print(f"Second check of value {result_from_second} complete")
async def third_execution(result_from_first):
# Moderately complex computation
await asyncio.sleep(5)
print(f"Third result {result_from_first+2}")
return result_from_first+2
async def check_third_execution(result_from_third):
# Computationally complex function which take a lot of time to compute
await asyncio.sleep(10)
print(f"Third check of value {result_from_third} complete")
async def main():
choice = random.choice([0, 1])
result_from_first = first_execution(choice)
# First part
coroutine_1 = check_first_execution(result_from_first)
if result_from_first==1:
coroutine_2 = second_execution(result_from_first)
results = await asyncio.gather(coroutine_1, coroutine_2)
elif result_from_first==0:
coroutine_3 = third_execution(result_from_first)
results = await asyncio.gather(coroutine_1, coroutine_3)
# Second part
list_results_from_first = [result_from_first+i for i in range(5)]
for first_result in list_results_from_first:
second_result = await second_execution(first_result)
check_second = await check_second_execution(second_result)
asyncio.run(main())
Код: Выделить всё
>> First result 1
>> First check of 1 complete
>> Second result 2
Код: Выделить всё
>> First result 1
>> Second result 2
>> First check of 1 complete
Во второй части (# Second part) это тоже происходило последовательно: Second_execution -> check_ Second_execution -> Second_execution -> check_ Second_execution ..., для пример (с выбором==1):
Код: Выделить всё
>> Second result 3
>> Second check of 3 complete
>> Second result 4
>> Second check of 4 complete
>> Second result 5
>> Second check of 5 complete
Код: Выделить всё
>> Second result 3
>> Second result 4
>> Second check 3 complete
>> Second result 5
>> Second check 4 complete
Любая помощь приветствуется.
Подробнее здесь: https://stackoverflow.com/questions/792 ... -tasks-ins