[英]How can I get unique key value to distinguish a variable between python multiprocessing.Process?
如何通過multiprocessing.Process獲取變量的進程間唯一鍵?
我已經嘗試過id(variable)
或以Eclipse調試模式的地址(例如A: <__main__.A object at 0x1ca9990>
)
但是,它們似乎無法區分過程中的變量。
這是為了檢查變量是否按我的意願共享。
這是我的測試代碼
class A(object):
def __init__(self):
self.variable = {'num' : 0}
def Rx(a):
time.sleep(1)
while 1:
time.sleep(2)
print "RX(id):", id(a.variable)
print "RX:", a.variable
def Tx(a):
while 1:
time.sleep(2)
print "TX(id):", id(a.variable)
a.variable['num'] += 1
print "TX:", a.variable
if __name__ == '__main__':
a = A()
rx = multiprocessing.Process(target=Rx, args=(a,))
tx = multiprocessing.Process(target=Tx, args=(a,))
rx.start()
tx.start()
這是輸出
TX(id): 33912768
TX: {'num': 1}
RX(id): 33912768
RX: {'num': 0}
TX(id): 33912768
TX: {'num': 2}
RX(id): 33912768
RX: {'num': 0}
TX(id): 33912768
TX: {'num': 3}
RX(id): 33912768
RX: {'num': 0}
TX(id): 33912768
TX: {'num': 4}
盡管它們(進程)打印相同的id(a.variable)
,但它們不共享變量。
id和內存地址(在CPython中是相關的)僅在單個進程中有意義。 您無法以嘗試的方式使用它們。 如果需要一些標識信息,則必須自己創建並將其放入要共享的對象中。
話雖如此,您沒有共享任何對象。 當您將普通對象作為參數傳遞給multiprocessing.Process
,它將為每個進程創建一個副本,並且不會共享任何更改。
在進程之間發送數據的最簡單方法是將其通過隊列,但是如果您確實需要共享一個可變對象,則multiprocessing
中有一些特殊的類允許這樣做: Value
和Array
用於簡單值,而Manager
用於更復雜的對象。
即:
from multiprocessing import Process, Manager
def f(d, l):
d[1] = '1'
d['2'] = 2
d[0.25] = None
l.reverse()
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
l = manager.list(range(10))
p = Process(target=f, args=(d, l))
p.start()
p.join()
print d
print l
有關更多詳細信息和一些使用它們的簡單示例,請參見https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.