Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python多处理类实例更新未正确执行_Python_Multiprocessing_Python Multiprocessing_Shared Memory_Multiprocess - Fatal编程技术网

Python多处理类实例更新未正确执行

Python多处理类实例更新未正确执行,python,multiprocessing,python-multiprocessing,shared-memory,multiprocess,Python,Multiprocessing,Python Multiprocessing,Shared Memory,Multiprocess,目前我需要在Python中使用多处理。 我的要求是在一个进程中创建一个对象列表,并在另一个进程中更新每个对象 我参考了堆栈溢出中的各种解决方案,发现问题仍然存在。 甚至我也尝试了以下方法 客户经理 因为我使用的是充当共享内存的Manager(),所以我担心为什么在一个进程中创建的对象不会反映在另一个进程中 这是否意味着我只能在Manager()中使用List/Dictionary/Int/String数据类型 即使多线程进程使用自己的内存空间,使用Manager()也可以充当共享内存 感谢您

目前我需要在Python中使用多处理。 我的要求是在一个进程中创建一个对象列表,并在另一个进程中更新每个对象

我参考了堆栈溢出中的各种解决方案,发现问题仍然存在。 甚至我也尝试了以下方法

  • 客户经理
  • 因为我使用的是充当共享内存的Manager(),所以我担心为什么在一个进程中创建的对象不会反映在另一个进程中

    这是否意味着我只能在Manager()中使用List/Dictionary/Int/String数据类型

    即使多线程进程使用自己的内存空间,使用Manager()也可以充当共享内存

    感谢您的帮助。如果我的理解有误,请告诉我

    请查找下面的代码段和相应的输出

    import multiprocessing
    
    class demo(object):
       def __init__(self):
           self.val = 100
    
       def update(self, g):
           self.val = g
    
       def __repr__(self):
           return "{}".format(self.__dict__)
    
    def update(sm):
       for obj in sm:
           obj.update(300)
           print( "\nUpdating as {}".format(obj))
    
       print("\nupdate completed")
       print(sm)
    
    
    def insert(sm):
       sm.append(demo())
       sm.append(demo())
       sm.append(demo())
       print("Insert completed")
       print(sm)
    
    L = multiprocessing.Manager().list()
    
    
    # creating new processes
    p1 = multiprocessing.Process(target=insert, args=(L,))
    p2 = multiprocessing.Process(target=update, args=(L,))
    
    
    # running process p1 to insert new record
    p1.start()
    p1.join()
    
    #  running process p2 to update record
    p2.start()
    p2.join()
    
    print("\nFinal output")
    print(L)
    
    输出:

    Insert completed
    [{'val': 100}, {'val': 100}, {'val': 100}]
    
    Updating as {'val': 300}
    
    Updating as {'val': 300}
    
    Updating as {'val': 300}
    
    update completed
    [{'val': 100}, {'val': 100}, {'val': 100}]
    
    Final output
    [{'val': 100}, {'val': 100}, {'val': 100}]