With time.sleep(1) below, first, test1()
is run every one second, then test2()
is run every one second:
import asyncio
import time
async def test1():
for _ in range(0, 3):
print('Test1')
time.sleep(1) # Here
async def test2():
for _ in range(0, 3):
print('Test2')
time.sleep(1) # Here
async def main():
await asyncio.gather(test1(), test2()) # Here
asyncio.run(main())
So, 6 seconds are taken to run test1()
and test2()
in total:
Test1 # 1 second
Test1 # 2 seconds
Test1 # 3 seconds
Test2 # 4 seconds
Test2 # 5 seconds
Test2 # 6 seconds
With asyncio.sleep(1) below, test1()
and test2()
are run every one second alternately:
import asyncio
async def test1():
for _ in range(0, 3):
print('Test1')
await asyncio.sleep(1) # Here
async def test2():
for _ in range(0, 3):
print('Test2')
await asyncio.sleep(1) # Here
async def main():
await asyncio.gather(test1(), test2()) # Here
asyncio.run(main())
So, only 3 seconds are taken to run test1()
and test2()
in total:
Test1 # 1 second
Test2 # 1 second
Test1 # 2 seconds
Test2 # 2 seconds
Test1 # 3 seconds
Test2 # 3 seconds
And, with time.sleep(0) below, first, test1()
is run at once, then test2()
is run at once:
import asyncio
import time
async def test1():
for _ in range(0, 3):
print('Test1')
time.sleep(0) # Here
async def test2():
for _ in range(0, 3):
print('Test2')
time.sleep(0) # Here
async def main():
await asyncio.gather(test1(), test2()) # Here
asyncio.run(main())
So, 0 second is taken to run test1()
and test2()
in total:
Test1 # 0 second
Test1 # 0 second
Test1 # 0 second
Test2 # 0 second
Test2 # 0 second
Test2 # 0 second
And, with asyncio.sleep(0) below, test1()
and test2()
are run at once alternately:
import asyncio
async def test1():
for _ in range(0, 3):
print('Test1')
await asyncio.sleep(0) # Here
async def test2():
for _ in range(0, 3):
print('Test2')
await asyncio.sleep(0) # Here
async def main():
await asyncio.gather(test1(), test2()) # Here
asyncio.run(main())
So, only 0 second is taken to run test1()
and test2()
in total:
Test1 # 0 second
Test2 # 0 second
Test1 # 0 second
Test2 # 0 second
Test1 # 0 second
Test2 # 0 second
Lastly, without time.sleep() or asyncio.sleep() below, first, test1()
is run at once, then test2()
is run at once:
import asyncio
async def test1():
for _ in range(0, 3):
print('Test1')
async def test2():
for _ in range(0, 3):
print('Test2')
async def main():
await asyncio.gather(test1(), test2()) # Here
asyncio.run(main())
So, 0 second is taken to run test1()
and test2()
in total:
Test1 # 0 second
Test1 # 0 second
Test1 # 0 second
Test2 # 0 second
Test2 # 0 second
Test2 # 0 second