With the code below I tried to print a bunch of things in parallel on a jupyter-notebook using a ThreadPoolExecutor
. Notice that with the function show()
, the output is not what you'd normally expect.
from concurrent.futures import ThreadPoolExecutor
import sys
items = ['A','B','C','D','E','F',
'G','H','I','J','K','L',
'M','N','O','P','Q','R',
'S','T','U','V','W','X','Y','Z']
def show(name):
print(name, end=' ')
with ThreadPoolExecutor(10) as executor:
executor.map(show, items)
# This outputs
# AB C D E F G H I J KLMNOP QR STU VW XY Z
But when I try with sys.stdout.write()
, I don't get this behavior.
def show2(name):
sys.stdout.write(name + ' ')
with ThreadPoolExecutor(10) as executor:
executor.map(show2, items)
# This gives
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
The weird thing is, I tried this both on jupyter notebook and by writing a .py file and running it. But with the latter I don't seem to get this problem. I tried searching but all I got was that print()
in python-3.x is thread safe. If it is indeed thread safe, could anyone explain why this is happening?