Search code examples
pythonmultithreadingstdinatomicpython-multithreading

Is stdin.readline() atomic in python?


With commands like cat big_file|python do.py, if do.py build multiple threads, and threads read data from stdin, do I need to use threading.Lock() to call stdin.readline?
Like:

with lock:
    line = stdin.readline()
do...

Solution

  • CPython's file API explicitly locks the file object around readline and other calls, which means readline() is indeed thread-safe. This mimics the historic behavior of C (POSIX) stdio which served as the basic of Python's file IO, and is not likely to change. Be warned, however, that this is not explicitly documented, so it could not be the case on other Python implementations, such as Jython or PyPy.