From 456a40ce9ce63371ebecfdff4657d23d9d047ecc Mon Sep 17 00:00:00 2001 From: David Wilson Date: Thu, 21 Sep 2017 03:21:16 +0530 Subject: [PATCH] core: synchronize Stream._output_buf by deferring send() Previously _output_buf was racy. This may or may not be cheaper than simply using a lock, but it requires much less code, so I prefer it for now. --- mitogen/core.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/mitogen/core.py b/mitogen/core.py index f67554c1..cdff71d2 100644 --- a/mitogen/core.py +++ b/mitogen/core.py @@ -624,16 +624,19 @@ class Stream(BasicStream): if not self._output_buf: broker.stop_transmit(self) - def send(self, msg): - """Send `data` to `handle`, and tell the broker we have output. May - be called from any thread.""" + def _send(self, msg): IOLOG.debug('%r._send(%r)', self, msg) pkt = struct.pack('>hhLLL', msg.dst_id, msg.src_id, msg.handle, msg.reply_to or 0, len(msg.data) ) + msg.data - self._output_buf += pkt # TODO: It's actually possible for this to race + self._output_buf += pkt self._router.broker.start_transmit(self) + def send(self, msg): + """Send `data` to `handle`, and tell the broker we have output. May + be called from any thread.""" + self._router.broker.defer(self._send, msg) + def on_disconnect(self, broker): super(Stream, self).on_disconnect(broker) self._router.on_disconnect(self, broker)