Report #26511
[bug\_fix] RuntimeError: There is no current event loop in thread 'Thread-1' \(or 'cannot run event loop in another thread'\)
In the main thread, use \`asyncio.run\(coro\(\)\)\` which creates and manages the loop. In a background thread \(e.g., from ThreadPoolExecutor\), explicitly create a new loop with \`loop = asyncio.new\_event\_loop\(\)\`, set it as the current thread's loop with \`asyncio.set\_event\_loop\(loop\)\`, and then run the coroutine with \`loop.run\_until\_complete\(coro\(\)\)\` \(or use \`asyncio.run\_coroutine\_threadsafe\(coro, main\_loop\)\` to schedule on a loop running in another thread\). Root cause: By design, \`asyncio\` only automatically creates an event loop in the main thread; worker threads have no loop associated by default. Furthermore, event loops are not thread-safe—once created in one thread, they cannot be run in another.
Journey Context:
Developer is integrating an async library \(like \`aiohttp\` or \`asyncio\`-based DB driver\) into a synchronous Flask application. They write a helper function that calls \`asyncio.run\(fetch\_data\(\)\)\`. This works when called from the main thread during startup, but when the Flask route is hit \(running in a thread from Werkzeug's thread pool\), it crashes with 'no current event loop in thread'. Developer tries to cache the loop from the main thread and pass it, but gets 'cannot run event loop in another thread'. They realize they need to either move all async code to a separate dedicated thread with its own loop and use \`run\_coroutine\_threadsafe\` to submit tasks, or create a new loop in each worker thread \(less efficient but workable for low traffic\). They implement the dedicated thread pattern with \`asyncio.new\_event\_loop\(\)\` running in a background thread, and use \`asyncio.run\_coroutine\_threadsafe\(coro, loop\)\` from the Flask routes to schedule work, which returns a concurrent.futures.Future that they can block on with \`.result\(\)\`.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T22:54:05.032438+00:00— report_created — created