如何在Python中让多个进程长期写入同一个文件?

问题描述 投票:0回答:1

我在Python中使用多进程,每个进程执行相同的程序,从一些pkl文件中读取数据,这些文件存储字典,根据这些pkl分析新数据,并用新结果更新相同的pkl文件。

多处理只是用于加速执行速度,理想情况下它们应该像执行程序的单个进程一样工作。也就是说,这些 pkl 文件在运行该程序的循环的每次迭代时都会更新。

实际上,他们可能会一起更新这些 pkl 文件,或者如果进程 A 正在读取 pkl 文件,而进程 B 正在写入其中,则导致 A 读取损坏的值。

谁能帮我理解如何解决这个问题?

python multiprocessing
1个回答
0
投票

如果理想情况下它应该像一个进程一样运行,则只需使用一个进程,或者可能是

threading
模块。除非您需要“线程”(或分叉进程)来创建更多线程(或分叉进程),否则用不同的进程代替线程实际上并没有多大好处(据我所知)。 使用
threading
模块的一个好处是,您可以为读取某些 pkl 文件等设置锁定。它的工作原理或多或少是这样的:

import threading
lock = threading.Lock()
with lock: # put this in a function which is started as a thread.
    # do stuff needing lock
    stuff_needing_lock()
# when another thread has the lock, no other threads can run

只需使用线程和锁即可完成。

你也可以定义自己的锁类,它不会自动停止其他线程,但你可以调用 .require() 方法来等待另一个线程释放锁

class lock:
    def __init__(self):
        self.aquired = False
    def aquire(self):
        self.aquired = True
    def require(self):
        while self.aquired:
            pass # do nothing if another thread has aquired the lock.
    def release(self): # don’t call unless you aquired the lock
        self.aquired = False

请原谅我无法拼写 aquire 等。

你可以只使用文件系统锁,但我不知道如何在 python 中做到这一点。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.