I have my servers classes inherited from BaseServer:
class BaseServer(object):
def __init__(self, host, port):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.instance = asyncio.start_server(self.handle_connection, host = host, port = port)
async def handle_connection(self, reader: StreamReader, writer: StreamWriter):
pass
def start(self):
# wrapping coroutine into ensure_future to allow it to call from call_soon
# wrapping into lambda to make it callable
callback = asyncio.ensure_future(self.instance)
self.loop.call_soon(lambda: callback)
self.loop.run_forever()
self.loop.close()
def stop(self):
self.loop.call_soon_threadsafe(self.loop.stop)
@staticmethod
def get_instance():
return BaseServer(None, None)
I need two servers running in own thread to processing requests in parallel. But when I trying to run them as needed, only first server is running. Below how I run them:
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
async def run():
pool = ThreadPoolExecutor(max_workers=cpu_count())
await loop.run_in_executor(pool, Server1.get_instance().start)
await loop.run_in_executor(pool, Server2.get_instance().start)
loop.run_until_complete(run())
- What am I doing wrong? How to run each server in own thread?
- When
asyncio.set_event_loopis calling fromdef __init__I got next error:
RuntimeError: There is no current event loop in thread 'Thread-1'.
But if I remove asyncio.set_event_loop from def __init__ and move it to def start error disappears. Why this happened?