Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 41 additions & 40 deletions src/async_examples/concurrency.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,47 @@
import asyncio
import aiohttp
import time
import random


async def fake_api_call(delay, data):
await asyncio.sleep(delay)
return f"Processed: {data}"
import asyncio


async def cpu_bound_task(n):
result = 0
for i in range(n):
result += i**2
return result
async def get_endpoint(session: aiohttp.ClientSession, url: str) -> str:
async with session.get(url) as response:
return await response.text()


async def some_api_call(urls):
results = []
for url in urls:
res = await fake_api_call(1, url)
results.append(res)
return results


async def tasker():
results = []
for i in range(10):
task = asyncio.create_task(fake_api_call(0.5, f"data_{i}"))
result = await task
results.append(result)

return results


async def manga():
results = []

for i in range(5):
async_result = await fake_api_call(0.3, f"async_{i}")
results.append(async_result)

time.sleep(0.5)
summer = sum(range(100000))
results.append(f"Sync task {i} completed with sum: {summer}")
return results
async with aiohttp.ClientSession() as session:
results = []
for url in urls:
result = await get_endpoint(session, url)
results.append(result)
return results
return None


async def retry_with_backoff(func, max_retries=3):
last_exception = None
for attempt in range(max_retries):
try:
return await func()
except Exception as e:
last_exception = e
if attempt < max_retries - 1:
time.sleep(0.00001 * attempt)
raise last_exception


async def sorter(arr):
print("codeflash stdout: Sorting list")
await asyncio.sleep(0.00001)
for i in range(len(arr)):
swapped = False
for j in range(len(arr) - 1 - i):
if arr[j] > arr[j + 1]:
temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
swapped = True
if not swapped:
break
print(f"result: {arr}")
return arr
Loading