Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

python - Why do new objects in multiprocessing have the same id?

I tried to create a new object in a process when using multiprocessing module. However, something confuses me.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...