Do I need a lock here?

Diez B. Roggisch deets at nospam.web.de
Mon Oct 27 05:12:33 EDT 2008


jasiu85 schrieb:
> Hey,
> 
> Please take a look at the code of the two threads below:
> 
> COMMON_DICT = {}
> 
> def thread_1():
>     global COMMON_DICT
>     local_dict = prepare_dict()
>     COMMON_DICT = local_dict
> 
> def thread_2():
>     global COMMON_DICT
>     local_dict = COMMON_DICT
>     use_dict(local_dict)
> 
> Do I need a lock to protect the COMMON_DICT dictionary? AFAIK bytecode
> operations are atomic and in each thread there's only one crucial
> bytecode op: STORE_NAME in the first thread and LOAD_NAME in the
> second one. So I suspect that everything will work just fine. Am I
> right?

Depending on what you mean by "right".

The above is not enough to judge what is really happening. But depending 
on the execution order, thread_1 overwrites the reference in COMMON_DICT 
*after* thread_2 has altered it.

But it won't crash or anything. If that's right for you.

Diez



More information about the Python-list mailing list