When the main thread is closed,I’m trying to close the event loop,but there’s a problem.
That’s the errors
Traceback (most recent call last):
File "/Users/liuzhichao/liuzhichao/trunk/code/TrunkPort/TrunkPortGateway/main.py", line 65, in <module>
app.stop()
File "/Users/liuzhichao/liuzhichao/trunk/code/TrunkPort/TrunkPortGateway/app.py", line 40, in stop
self.__api_service.stop()
File "/Users/liuzhichao/liuzhichao/trunk/code/TrunkPort/TrunkPortGateway/web/__init__.py", line 53, in stop
self.__loop.run_until_complete(close_task)
File "uvloop/loop.pyx", line 1450, in uvloop.loop.Loop.run_until_complete
File "uvloop/loop.pyx", line 1443, in uvloop.loop.Loop.run_until_complete
File "uvloop/loop.pyx", line 1351, in uvloop.loop.Loop.run_forever
File "uvloop/loop.pyx", line 480, in uvloop.loop.Loop._run
RuntimeError: this event loop is already running.
That’s my code
import uvloop
import asyncio
import logging
from functools import partial
from threading import Thread
from conf import settings
from .app import app
class ApiService:
def __init__(self, host, port):
self.host = host
self.port = port
self.__server = None
self.__loop = None
def run(self):
self.__loop = uvloop.new_event_loop()
thread = Thread(target=partial(self._thread_main, self.__loop), name="api-service")
thread.setDaemon(True)
thread.start()
def _thread_main(self, loop):
logging.info("ApiService Listening on http://{}:{}".format(self.host, self.port))
asyncio.set_event_loop(loop)
serv_coro = app.create_server(
host=self.host, port=self.port, return_asyncio_server=True, debug=settings.DEBUG
)
serv_task = asyncio.ensure_future(serv_coro, loop=self.__loop)
self.__server = self.__loop.run_until_complete(serv_task)
self.__server.after_start()
self.__loop.run_forever()
def stop(self):
if self.__loop is None or self.__server is None:
return
self.__loop.stop()
self.__server.before_stop()
# Wait for server to close
close_task = self.__server.close()
self.__loop.run_until_complete(close_task)
# Complete all tasks on the loop
for connection in self.__server.connections:
connection.close_if_idle()
self.__server.after_stop()
and I’m trying to closed event loop,e.g loop.closed()
,but there‘s still a problem.
Thank you very much ~