I wrote a simple program in Python:
from random import random from threading import Thread from time import sleep def write_to_file(i): sleep(random()) with open("test.txt", "a") as f: f.write(f"{i}\n") for i in range(20): Thread(target=write_to_file, args=[i]).run() I'd expect this program to write numbers from 0-19 to test.txt in random order. Instead, the program writes 0-19 in order, and it takes a few seconds to complete, signifying that it executed threads one after the other, in order.
How does this work? Does with open(...) block every other thread from running that also has with open(...) on the same file?