Python多处理,使用对象在进程之间共享数据

时间:2018-09-27 23:16:55

标签: python multiprocessing

我正在尝试使用一个名为“内存”的通用对象临时存储一个值,该值由一个名为“ Writer_process”的进程写入并由“ Reader_process”读取,但读取器仅返回存储在“ Memory”中的原始值。

import multiprocessing
import time

class Writer_process(multiprocessing.Process):
    def __init__(self, val, memory):
        super().__init__()
        self.val = val
        self.memory = memory

    def run(self):
        cont = 0
        while True:
            cont += self.val
            self.memory.num = cont
            time.sleep(1)

class Reader_process(multiprocessing.Process):
    def __init__(self, val, memory):
        super().__init__()
        self.val = val
        self.memory = memory

    def run(self):
        while True:
            print(self.memory.num)
            time.sleep(self.val)

class Memory():
    num = 0

if __name__ == '__main__':
    memory = Memory()
    writer = Writer_process(1, memory)
    reader = Reader_process(1, memory)
    writer.start()
    reader.start()

1 个答案:

答案 0 :(得分:1)

谢谢Eli Korvigo我使用“管理器”管理对内存的访问来解决了这个问题,一个名为“值”的特定多处理对象可以让我存储单个数据并在不同进程之间共享

import multiprocessing
import time

class Writer_process(multiprocessing.Process):
    def __init__(self, val, memory):
        super().__init__()
        self.val = val
        self.memory = memory

    def run(self):
        cont = 0
        while True:
            cont += 1
            self.memory.value = cont
            time.sleep(self.val)

class Reader_process(multiprocessing.Process):
    def __init__(self, val, memory):
        super().__init__()
        self.val = val
        self.memory = memory

    def run(self):
        while True:
            self.datum = self.memory.value
            print(self.datum)
            time.sleep(self.val)

if __name__ == '__main__':
    with multiprocessing.Manager() as manager:
        memory = manager.Value('i', 0)
        writer = Writer_process(1, memory)
        reader = Reader_process(1, memory)
        writer.start()
        reader.start()
        writer.join()
        reader.join()