Skip to content

Output.clear_output() in a thread does not block until the output is cleared #3260

@eriknw

Description

@eriknw

Description

I create an Output object on the main thread and display something on it. Then, in another thread, I try to clear the output and display other things on it. There is a surprising race condition that causes some of the things in the new thread to not be displayed. Specifically, the call to out.clear_output() does not clear the output right away, so subsequent calls to the Output object will get dropped once clear_output finally takes effect.

Reproduce

From IPython notebook:

import string
import threading
from ipywidgets import Output
from IPython.display import display
import time

out = Output()
out.append_stdout('hello\n')
display(out)
def bad_clear(out):
    out.clear_output()
    for c in string.ascii_letters:
        out.append_stdout(c)
        time.sleep(.01)

thread = threading.Thread(target=bad_clear, args=[out])
thread.start()

For me, the output from the first cell can be jklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. abcdefghi got cleared!

To work around this, I currently do the following:

def good_clear(out):
    out.clear_output()
    while out.outputs:
        time.sleep(0.01)  # NEW
    for c in string.ascii_letters:
        out.append_stdout(c)
        time.sleep(.01)

thread = threading.Thread(target=good_clear, args=[out])
thread.start()

Expected behavior

I expect the output of out to be cleared in bad_clear immediately after out.clear_output() is called. If it's too troublesome to do this, then I at least expect a note in the docstring and the example added here: #1794

Context

Previous relevant issues: #1794 #1722 #1752

  • ipywidgets version: 7.6.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions