Skip to content Skip to sidebar Skip to footer

Why Multiple Processes Have The Same Object Id In Python

The code as following: class T1(): def mytest(self,obj): print id(obj) if __name__=='__main__': obj = {'a':'b'} t1 = T1() p1 = Process(name='p1',target=t1.

Solution 1:

The above code print out the same id, are the two process sharing the same object?

No, the identifier is only guaranteed to be unique for a given process. In your case two objects in two different processes happen to have the same identifier, because both processes execute the same code (this behavior is not guaranteed, it just has a high probability of happening).

Another question when I change the dict to another regular object, it would throw exception as:TypeError: 'Test' object is not iterable How can I share a regular object between python processes please.

args requires an iterable of arguments. (obj) is equivalent to just obj, so if obj is not an iterable, you get this error. What you wanted to write, I'm guessing, is (obj,), which would create a tuple, and in this case obj can be any object (as long as it's pickle-able, of course).

Post a Comment for "Why Multiple Processes Have The Same Object Id In Python"