allows threadsafe sys.stdout.flush from background threads

depends on #5668
closes #5408