From 48291e62a610ff80a7ad56dca6d26aae50d46231 Mon Sep 17 00:00:00 2001 From: martsforever Date: Sun, 7 Sep 2025 00:02:44 +0800 Subject: [PATCH] feat: test_to_thread --- app/utils/test_to_thread.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 app/utils/test_to_thread.py diff --git a/app/utils/test_to_thread.py b/app/utils/test_to_thread.py new file mode 100644 index 0000000..aeb2b54 --- /dev/null +++ b/app/utils/test_to_thread.py @@ -0,0 +1,36 @@ +import asyncio +import time + + +async def main(): + common_counter = 0 + + def sync_delay(name: str): + nonlocal common_counter + # current_counter = common_counter + time.sleep(0.5) + print(f"{name},111\n") + print(f"{name},222\n") + common_counter = common_counter + 1 + print(f"{name},333\n") + print(f"{name}[common_counter]:{common_counter}\n") + print(f"{name},444\n") + + start_time = time.time() + + # sync_delay("1") + # sync_delay("2") + # sync_delay("3") + + await asyncio.gather( + asyncio.create_task(asyncio.to_thread(sync_delay, name="A")), + asyncio.create_task(asyncio.to_thread(sync_delay, name="B")), + asyncio.create_task(asyncio.to_thread(sync_delay, name="C")), + ) + + print("common_counter", common_counter) + + print(f"耗时: {time.time() - start_time}s") + + +asyncio.run(main())