Do I need a lock here?
Duncan Booth
duncan.booth at invalid.invalid
Mon Oct 27 07:58:33 EDT 2008
jasiu85 <jasiu85 at gmail.com> wrote:
> 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?
>
Possibly, but without further information it is impossible to tell.
You have one thing wrong though: bytecode operations are not all atomic.
For example STORE_NAME will remove a reference to the object previously
stored under a name and that could trigger code in a __del__ method or a
weak reference callback. That callback code will execute in the same thread
as the STORE_NAME, but while it is executing you could get a context switch
to another thread.
None of that will prevent the store working, and it may not be at all
applicable to your data structures, but in general any operation which can
release complex objects is not thread safe.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list