[英]Is this code safe with python threading module?
my.txt 文件是否总是包含 100 行? 此代码是否保证没有数据丢失?
import threading
import os
class Worker(threading.Thread):
def __init__(self, name):
super().__init__()
self.name = name
def run(self):
os.system("echo {} >> my.txt".format(self.name))
for i in range(100):
name = "thread {}".format(i)
t = Worker(name)
t.start()
您正在使用>>
进行 shell 重定向。 这将以 append 模式打开文件,并且操作系统保证在该模式下所有数据都写入文件末尾,因此不会丢失任何数据。 然而,当写入大量数据时,来自不同来源的行可能会以不可预知的方式混合在一起。
并不是真的需要为您编写的每一行启动一个新的 shell。 您可以使用with open("my.txt", "a") as f: ...
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.