diff --git a/minecraft/networking/connection.py b/minecraft/networking/connection.py index 010997b..f9a8165 100644 --- a/minecraft/networking/connection.py +++ b/minecraft/networking/connection.py @@ -133,6 +133,7 @@ class Connection(object): # This lock is re-entrant because it may be acquired in a re-entrant # manner from within an outgoing packet self._write_lock = RLock() + self.packet_listener_lock = RLock() self.networking_thread = None self.new_networking_thread = None @@ -274,7 +275,8 @@ class Connection(object): else self.early_packet_listeners if early and not outgoing \ else self.outgoing_packet_listeners if not early \ else self.early_outgoing_packet_listeners - target.append(packets.PacketListener(method, *packet_types, **kwds)) + with self.packet_listener_lock: + target.append(packets.PacketListener(method, *packet_types, **kwds)) def register_exception_handler(self, handler_func, *exc_types, **kwds): """ @@ -587,14 +589,17 @@ class Connection(object): self.handle_exit() def _react(self, packet): - try: - for listener in self.early_packet_listeners: - listener.call_packet(packet) - self.reactor.react(packet) - for listener in self.packet_listeners: - listener.call_packet(packet) - except IgnorePacket: - pass + # Let live code reload replace bound listeners without racing a packet + # dispatch. RLock permits handlers to register listeners themselves. + with self.packet_listener_lock: + try: + for listener in self.early_packet_listeners: + listener.call_packet(packet) + self.reactor.react(packet) + for listener in self.packet_listeners: + listener.call_packet(packet) + except IgnorePacket: + pass class NetworkingThread(threading.Thread):