Open interkosmos opened 4 years ago
@interkosmos mixing threads with asyncio is generally not recommended.
If you need to (for example you have a not async written code or something cpu heavy) have a look at ProcessPoolExecutor
or ThreadPoolExecutor
. They allow you to run code in parallel to async code but keep the async loop in control.
You seem to be right. I couldn’t get it running inside a Thread class, but it works using:
def run(self, loop):
try:
future = asyncio.gather(self.broker_coroutine(self.config, loop),
loop=loop)
loop.run_until_complete(future)
loop.run_forever()
loop.run_until_complete(self.broker.shutdown())
loop.close()
except KeyboardInterrupt:
loop.close()
except:
loop.close()
def start(self):
loop = asyncio.new_event_loop()
thread = Thread(target=lambda: self.run(loop), daemon=True)
thread.start()
Therefore, it’s a Python and not an HBMQTT issue.
How can I run an HBMQTT broker instance inside a Python thread? The following minimal example doesn’t work:
This basic example crashes:
But running the coroutine
test_coroutine()
instead just works as intended. Ifasyncio.set_event_loop(self.loop)
is added the thread starts but immediately finishes:Output: