मैं वैश्विक ऑब्जेक्ट रखना चाहता हूं जो न्यूनतम प्रक्रियाओं के साथ सभी प्रक्रियाओं द्वारा साझा और अद्यतन किया जाता है।मैं प्रक्रियाओं के बीच कक्षा कैसे साझा कर सकता हूं?
import multiprocessing
class Counter(object):
def __init__(self):
self.value = 0
def update(self, value):
self.value += value
def update(counter_proxy, thread_id):
counter_proxy.value.update(1)
print counter_proxy.value.value, 't%s' % thread_id, \
multiprocessing.current_process().name
return counter_proxy.value.value
def main():
manager = multiprocessing.Manager()
counter = manager.Value(Counter, Counter())
pool = multiprocessing.Pool(multiprocessing.cpu_count())
for i in range(10):
pool.apply(func = update, args = (counter, i))
pool.close()
pool.join()
print 'Should be 10 but is %s.' % counter.value.value
if __name__ == '__main__':
main()
परिणाम यह है - 10 नहीं बल्कि शून्य। ऐसा लगता है कि ऑब्जेक्ट का साझा मूल्य अपडेट नहीं किया गया है। मैं इस तरह के मूल्य को कैसे लॉक और अपडेट कर सकता हूं?
0 t0 PoolWorker-2
0 t1 PoolWorker-3
0 t2 PoolWorker-5
0 t3 PoolWorker-8
0 t4 PoolWorker-9
0 t5 PoolWorker-2
0 t6 PoolWorker-7
0 t7 PoolWorker-4
0 t8 PoolWorker-6
0 t9 PoolWorker-3
Should be 10 but is 0.
वर्तमान @dano द्वारा सबसे अच्छा समाधान - मैं कक्षा प्रॉक्सी के साथ कस्टम प्रबंधक मिलाया।
import multiprocessing
from multiprocessing.managers import BaseManager, NamespaceProxy
class Counter(object):
def __init__(self):
self.value = 0
def update(self, value):
self.value += value
def update(counter_proxy, thread_id):
counter_proxy.update(1)
class CounterManager(BaseManager):
pass
class CounterProxy(NamespaceProxy):
_exposed_ = ('__getattribute__', '__setattr__', '__delattr__', 'update')
def update(self, value):
callmethod = object.__getattribute__(self, '_callmethod')
return callmethod(self.update.__name__, (value,))
CounterManager.register('Counter', Counter, CounterProxy)
def main():
manager = CounterManager()
manager.start()
counter = manager.Counter()
pool = multiprocessing.Pool(multiprocessing.cpu_count())
for i in range(10):
pool.apply(func = update, args = (counter, i))
pool.close()
pool.join()
print 'Should be 10 but is %s.' % counter.value
if __name__ == '__main__':
main()
आप 'NamespaceProxy' के बारे में कैसे सीखा? मुझे कहीं भी इसका दस्तावेज नहीं मिल रहा है। – Seanny123