Python 同时附加到一个文件

Python appending to a file concurrently

我在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()

我希望这个程序能以随机顺序写入从 0-19 到 test.txt 的数字。相反,程序按顺序写入 0-19,需要几秒钟才能完成,表示它按顺序一个接一个地执行线程。

这是如何工作的? with open(...) 是否会阻止来自 运行 且在同一文件上也有 with open(...) 的所有其他线程?

不用运行方法,改成start,运行方法是调用主线程,相当于普通函数,start只会创建一个新线程,你在这里等待几秒钟,因为你设置了sleep(random()),你可以评论这行:

from threading import Thread

def write_to_file(i):
    with open("test.txt", "a") as f:
        f.write(f"{i}\n")

for i in range(20):
    Thread(target=write_to_file, args=[i]).start()

Does with open(...) block every other thread from running that also has with open(...) on the same file?

不,不是。

run 线程的方法启动并加入线程,这意味着它等待线程在每次迭代中加入。要使其并行,您必须调用 start 而不是 run 然后 join 一次调用所有线程。

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")


threads = []

for i in range(20):
    thread = Thread(target=write_to_file, args=[i])
    thread.start()
    threads.append(thread)

for thread in threads:
    thread.join()