bsam
bsam

Reputation: 930

Behaviour of deepcopy while changing object to be copied

If an object that's being copied (using the deepcopy function from python 2.7's copy library) by thread A is changed, concurrently, by thread B, what is expected to happen?

EDIT: The object to be changed is a dictionary, and the change would be the removal of a single key from it. In my case, copying either the old dictionary or the new one would be ok - I just wanted to assure that weirder indefinite states wouldn't happen.

Upvotes: 0

Views: 264

Answers (1)

jsbueno
jsbueno

Reputation: 110311

Code like will not only break the interpreter because they have put a GIL (Global Interpreter Lock) in Python. So, you will still have your copied object in an indefinite state, but thanks to the GIL, each of the sub-objects inside it will be itself a consistent and complete Python object. Which sub-objects will end up in the copied state are just a matter of chance, however.

If, as you say, the other thread will change a single dictionary value, and it is not important where your copy will end up with the old or new value, there is no danger at all: Python ensures the integrity of the dictionary object in any case.

If you have multiple possible concurrent changes on a complex object, use a manual lock to ensure one state you are "seeing" as the state the copy will be.

Upvotes: 3

Related Questions