問題描述
我嘗試在使用多處理模塊時在進程中創建新對象.但是,有些事情讓我感到困惑.
I tried to create a new object in a process when using multiprocessing module. However, something confuses me.
當我使用多處理模塊時,新對象的id是一樣的
When I use multiprocessing module, the id of the new object is the same
for i in range(4):
p = multiprocessing.Process(target=worker)
p.start()
def worker():
# stanford named entity tagger
st = StanfordNERTagger(model_path,stanford_ner_path)
print id(st) # all the processes print the same id
但是當我使用線程時,它們是不同的:
But when I use threading, they are different:
for i in range(4):
p = threading.Thread(target=worker)
p.start()
def worker():
# stanford named entity tagger
st = StanfordNERTagger(model_path,stanford_ner_path)
print id(st) # threads print differnt ids
我想知道為什么它們不同.
I am wondering why they are different.
推薦答案
idCPython 中的 返回給定對象的指針.由于線程共享地址空間,一個對象的兩個不同實例將被分配在兩個不同的位置,返回兩個不同的 id(也稱為虛擬地址指針).
id in CPython returns the pointer of the given object. As threads have shared address space, two different instances of an object will be allocated in two different locations returning two different ids (aka virtual address pointers).
對于擁有自己地址空間的獨立進程來說,情況并非如此.碰巧他們得到了相同的地址指針.
This is not the case for separate processes which own their own address space. By chance, they happen to get the same address pointer.
請記住,地址指針是虛擬的,因此它們表示進程地址空間本身的偏移量.這就是為什么它們是相同的.
Keep in mind that address pointers are virtual, therefore they represent an offset within the process address space itself. That's why they are the same.
通常最好不要依賴 id() 來區分對象,因為新對象可能會得到舊對象的 id,隨著時間的推移很難跟蹤它們.它通常會導致棘手的錯誤.
It is usually better not to rely on id() for distinguishing objects, as new ones might get ids of old ones making hard to track them over time. It usually leads to tricky bugs.
這篇關于為什么多處理中的新對象具有相同的 id?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!