diff --git a/src/async_examples/concurrency.py b/src/async_examples/concurrency.py index 7be2352..6c76287 100644 --- a/src/async_examples/concurrency.py +++ b/src/async_examples/concurrency.py @@ -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