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

2024-05-05 23:39:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

  1. 自定义管理器https://docs.python.org/2.7/library/multiprocessing.html#customized-managers
  2. How can I share a class between processes?
  3. multiprocessing: How do I share a dict among multiple processes?

因为我使用的是充当共享内存的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}]


Tags: 对象self进程demodefasmanagerupdate