xxxxxxxxxx
def blocking_io():
print(f"start blocking_io at {time.strftime('%X')}")
# Note that time.sleep() can be replaced with any blocking
# IO-bound operation, such as file operations.
time.sleep(1)
print(f"blocking_io complete at {time.strftime('%X')}")
async def main():
print(f"started main at {time.strftime('%X')}")
await asyncio.gather(
asyncio.to_thread(blocking_io),
asyncio.sleep(1))
print(f"finished main at {time.strftime('%X')}")
asyncio.run(main())
# Expected output:
#
# started main at 19:50:53
# start blocking_io at 19:50:53
# blocking_io complete at 19:50:54
# finished main at 19:50:54
xxxxxxxxxx
import asyncio
async def get_some_values_from_io():
# Some IO code which returns a list of values
vals = []
async def fetcher():
while True:
io_vals = await get_some_values_from_io()
for val in io_vals:
vals.append(io_vals)
async def monitor():
while True:
print (len(vals))
await asyncio.sleep(1)
async def main():
t1 = asyncio.create_task(fetcher())
t2 = asyncio.create_task(monitor())
await asyncio.gather(t1, t2)
asyncio.run(main())
xxxxxxxxxx
import asyncio
async def get_data_from_io():
async def process_data(data):
async def main():
while true:
data = await get_data_from_io()
await process_data(data)
asyncio.run(main())