使用多重处理时,有没有一种方法可以防止对象的隐式复制? 蟒蛇

问题描述

我正在尝试使串行数据侦听器。由于我的设备连续发送数据,因此我尝试使用True True循环捕获它们。为了执行更多代码,我将此循环外包给另一个进程。所有这些结合在一个特定的类中。 此类的对象位于主进程中,而循环例程是通过另一个进程中的方法启动的。为了关闭此循环,我在while循环内测试了obect属性是否正在更改。但是,如果我在主流程中更改了属性,则该属性在其他流程中没有更改,因为原始对象似乎已被复制。

问题是,有什么办法可以防止这种复制,或者侦听器任务是否有其他解决方法

这是我的问题的简化版本:(请注意,worker函数模拟串行数据流)

import random
from multiprocessing import Process,Pipe
import time

def worker(conn):
    while True:
        b = random.random()
        print('SEND: ',b)
        conn.send(b)
        time.sleep(1)


class A:

    def __init__(self):
        self.datastream_check = False
        self.listen_process = None

    def close(self):
        self.datastream_check = False

    def nested_read(self,conn):
        while self.datastream_check: # this attribute is always True
            print('REC: ',conn.recv())
            time.sleep(1)
        else:
            self.listen_process.kill()
            self.listen_process.join()
            self.listen_process = None


    def read_datastream(self):
        self.datastream_check = True
        self.listen_process = Process(target=self.nested_read,args=(parent_conn,))
        self.listen_process.start()


if __name__ == '__main__':

    parent_conn,child_conn=Pipe()
    datastream = Process(target=worker,args=(child_conn,))
    datastream.start()

    a = A()
    a.read_datastream()

    time.sleep(10)
    a.close() # this call alters the object in main,so the other object is not effected



解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)