diff --git a/kasa/protocol.py b/kasa/protocol.py index 14de9c6c..e2f94626 100755 --- a/kasa/protocol.py +++ b/kasa/protocol.py @@ -156,7 +156,11 @@ class TPLinkSmartHomeProtocol: def __del__(self) -> None: if self.writer and self.loop and self.loop.is_running(): - self.writer.close() + # Since __del__ will be called when python does + # garbage collection is can happen in the event loop thread + # or in another thread so we need to make sure the call to + # close is called safely with call_soon_threadsafe + self.loop.call_soon_threadsafe(self.writer.close) self._reset() @staticmethod