Tell HN: Python's print function is thread-unsafe
13 points| kerneloops | 2 years ago
from threading import Thread
def target(x):
for _ in range(100000): print(x)
Thread(target=target, args=['a' * 10]).start()
Thread(target=target, args=['b' * 10]).start()
Python could print out not only interleaved bytes (aaabbbabab), but also null bytes and uninitialized memory, thanks to non-synchronized buffering.
kerneloops|2 years ago
C printf: MT-Safe locale.
C++ std::cout: safe, unless you call sync_with_stdio(false).
JVM System.out.println: safe in common JVMs.
C# Console.WriteLine: safe.
Go fmt.Printf: safe.
Rust println!: safe.
Ruby puts: safe.
So it seems that Python is the outlier here.
vitaut|2 years ago
See https://vitaut.net/posts/2023/print-in-cpp23/.
eesmith|2 years ago
antman|2 years ago
https://superfastpython.com/thread-safe-print-in-python/
Python logging is thread safe if you want to use it for output
cratermoon|2 years ago
The problem with threads: https://ieeexplore.ieee.org/document/1631937
ansgri|2 years ago