Python并发追加到文件
我用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要用run方法,改成start,run方法是调用主线程,相当于普通函数,start只会创建一个新线程,你在这里等几秒因为你设置了sleep(random( )),你可以评论这一行:
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:
不,事实并非如此。
线程的 run 方法启动并加入线程,这意味着每次迭代都会等待线程加入。要使其并行,您必须调用
start
而不是run
,然后立即join
所有线程。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 callstart
instead ofrun
thenjoin
all threads at once.