Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add locking around output buffer #123

Merged
merged 3 commits into from
Apr 15, 2016
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions ipykernel/iostream.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import os
import threading
import sys
import threading
import uuid
import warnings
from io import StringIO, UnsupportedOperation
Expand Down Expand Up @@ -222,6 +223,7 @@ def __init__(self, session, pub_thread, name, pipe=None):
self._flush_lock = threading.Lock()
self._flush_timeout = None
self._io_loop = pub_thread.io_loop
self._buffer_lock = threading.Lock()
self._new_buffer()

def _is_master_process(self):
Expand Down Expand Up @@ -314,7 +316,9 @@ def write(self, string):
string = string.decode(self.encoding, 'replace')

is_child = (not self._is_master_process())
self._buffer_lock.acquire(True)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can use with self._buffer_lock in both places

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To expand a bit: if the code between acquire() and release() throws an error for some reason, the lock would never be released. You can make sure that some 'after' code is run even if an exception is thrown:

lock.acquire()
try:
    do_stuff()
finally:
    lock.release()

But locks support a more convenient way to achieve the same thing:

with lock:
    do_stuff()

self._buffer.write(string)
self._buffer_lock.release()
if is_child:
# newlines imply flush in subprocesses
# mp.Pool cannot be trusted to flush promptly (or ever),
Expand All @@ -333,12 +337,15 @@ def writelines(self, sequence):

def _flush_buffer(self):
"""clear the current buffer and return the current buffer data"""

self._buffer_lock.acquire(True)
data = u''
if self._buffer is not None:
buf = self._buffer
self._new_buffer()
data = buf.getvalue()
buf.close()
self._buffer_lock.release()
return data

def _new_buffer(self):
Expand Down