yagwr.async_in_thread: Running an asyncio loop in a thread
- yagwr.async_in_thread.module_logger = <Logger yagwr.async_in_thread (WARNING)>
The default logger of this module
- class yagwr.async_in_thread.AsyncInThread(coro, name='AsyncThread', log=<Logger yagwr.async_in_thread (WARNING)>)
Bases:
objectThis class allows to execute an asyncio loop in a thread.
Sometimes you need to execute asynchronous code in a seprate thread inside a synchronous program. Starting the ioloop in a thread is a chore. This class allows you to do that.
Inside your main task, you can get the running loop via
asyncio.get_running_loop(). Theloopwill have an extra attributethread_controllerwith a reference to theAsyncInThreadobject.Example:
import asyncio from yagwr.async_in_thread import AsyncInThread async def main_task(): print("This is the main task") while True: print("Doing stuff") await some_other_function() await asyncio.sleep(1) ath = AsyncInThread(main_task()) ath.start() try: while True: execute_task() if should_quit(): break finally: ath.stop()
- Parameters
coro (coroutine) – a coroutine, the main task. When
stop()is executed, the task is cancelled. The task is responsible to cancel other tasks that it might have spawned.name (str) – a string used in logging and for the name of the thread
log (logging.Logger) – the logger where debug info is logged to.
- start()
- stop()