Python并发追加到文件

发布于 2025-01-11 14:48:07 字数 495 浏览 0 评论 0原文

我用 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(...) 的所有其他线程运行?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甚是思念 2025-01-18 14:48:07

不要用run方法,改成start,run方法是调用主线程,相当于普通函数,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()

Don't use the run method, change it to start, the run method is to call the main thread, equivalent to the ordinary function, start will only create a new thread, you wait a few seconds here because you set sleep(random()), you can comment this line:

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()
月牙弯弯 2025-01-18 14:48:07

with open(...) 是否会阻止同一文件上也有 with open(...) 的所有其他线程运行?

不,事实并非如此。

线程的 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()

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

No, it doesn't.

run method of a thread starts and joins the thread which means that it waits for a thread to be joint for every iteration. To make it parallel you must call start instead of run then join all threads at once.

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文