简体   繁体   English

此代码与 python 线程模块是否安全?

[英]Is this code safe with python threading module?

Is my.txt file always hold 100 lines? my.txt 文件是否总是包含 100 行? Does this code guarantee that there is no data loss?此代码是否保证没有数据丢失?

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

You are using >> for the shell redirection.您正在使用>>进行 shell 重定向。 This opens the file in append mode, and the OS guarantees that all data is written at the end of the file in that mode, so no data will get lost.这将以 append 模式打开文件,并且操作系统保证在该模式下所有数据都写入文件末尾,因此不会丢失任何数据。 However, when writing a lot of data, lines from different sources may be intermingled in unpredictable ways.然而,当写入大量数据时,来自不同来源的行可能会以不可预知的方式混合在一起。

Launching a new shell for each line you write isn't really required.并不是真的需要为您编写的每一行启动一个新的 shell。 You can open files in append mode directly from Python using with open("my.txt", "a") as f: ... .您可以使用with open("my.txt", "a") as f: ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM