我有以下多个类,这些类在多个消费者之间共享(使用生产者/消费者方法)。我的问题涉及在此类上调用的方法。我需要实现锁还是经理类线程安全?

import multiprocessing as mp
from multiprocessing.manager import BaseManager

class SampleClass(object):

    def __init__(self):
        self._count = 0

    # Does locking need to be implemented here?
    def increment(self):
        self._count += 1

BaseManager.register('SampleClass', SampleClass)
manager = BaseManager()
manager.start()

instance = manager.SampleClass()

jobs = []
for i in range(0, 5):
    p = mp.Process(target=some_func, args=(instance,))
    jobs.append(p)
    p.start()

for p in jobs:
    p.join()

最佳答案

我想是这样。正如对另一个问题的评论所述:

  • multiprocessing: How do I share a dict among multiple processes?

  • 关于python - Python多处理管理器类对象线程/进程安全,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45316770/

    10-14 20:52