简体   繁体   English

Python多处理管理器类对象线程/进程安全

[英]Python multiprocessing manager class object thread/process safe

I have the following class that is shared between multiple consumers (using producer/consumer methodology). 我有以下几个在多个消费者之间共享的类(使用生产者/消费者方法)。 My question involves the methods called on this class. 我的问题涉及这个类上调用的方法。 Do I need to implement locks or is the manager class thread safe? 我需要实现锁定还是经理类线程安全?

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()

I think so. 我认同。 As said as a comment on this other question: 正如对此另一个问题的评论所说:

  1. multiprocessing: How do I share a dict among multiple processes? 多处理:如何在多个进程之间共享一个字典?

Is manager.dict() this process safe? manager.dict()这个过程安全吗?

@LorenzoBelli, if you're asking whether access to the manager is synchronized, I believe the answer is yes. @LorenzoBelli,如果你问是否同步访问经理,我相信答案是肯定的。 multiprocessing.Manager() returns an instance of SyncManager , the name of which suggests as much! multiprocessing.Manager()返回一个SyncManager实例 ,其名称同样表示!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM