如何在Python中控制多个进程对文件的访问

Lum*_*nos 5 python python-multithreading python-multiprocessing

我一直在寻找以下多处理问题的解决方案。

我在 record.py 模块中有一个 Record 类。记录类的职责是处理输入数据并将其保存到 JSON 文件中。Record 类有 put() 方法来更新 JSON 文件。

记录类在类装饰器中初始化。装饰器应用于各个子模块的大多数类。Decorator 提取它所装饰的每个方法的信息,并将数据发送到 Record 类的 put() 方法。Record 类的 put() 方法然后更新 JSON 文件。

问题是当不同的进程运行时,每个进程都会创建自己的记录对象实例,并且由于多个进程尝试更新相同的 json 文件,Json 数据会被损坏。此外,每个进程可能都有运行的线程尝试访问和更新相同的 JSON 文件。请让我知道如何解决这个问题。

class Record():
    def put(data):
        # read json file
        # update json file with new data
        # close json file

def decorate_method(theMethod):
    # Extract method details
    data = extract_method_details(theMethod)

    # Initialize record object
    rec = Record()
    rec.put(data)

class ClassDeco(cls):
    # This class decorator decorates all methods of the target class

    for method in cls():  #<----This is just a pseudo codebase
        decorate_method()

@ClassDeco
class Test()
    def __init__():
        pass

def run(a):
    # some function calls

if __name__ == "__main__":
    t = Test()
    p = Pool(processes=len(process_pool))
    p.apply_async(t.run, args=(10,))
    p.apply_async(t.run, args=(20,))
    p.close()
Run Code Online (Sandbox Code Playgroud)

Pos*_*shi 2

您应该在读取和写入文件之前锁定该文件。检查与 python 中的文件锁定相关的另一个问题:Locking a file in Python