Using a global dictionary with threads in Python

后端 未结 5 781
野性不改
野性不改 2020-11-29 21:55

Is accessing/changing dictionary values thread-safe?

I have a global dictionary foo and multiple threads with ids id1, id2, ..

5条回答
  •  难免孤独
    2020-11-29 22:16

    How it works?:

    >>> import dis
    >>> demo = {}
    >>> def set_dict():
    ...     demo['name'] = 'Jatin Kumar'
    ...
    >>> dis.dis(set_dict)
      2           0 LOAD_CONST               1 ('Jatin Kumar')
                  3 LOAD_GLOBAL              0 (demo)
                  6 LOAD_CONST               2 ('name')
                  9 STORE_SUBSCR
                 10 LOAD_CONST               0 (None)
                 13 RETURN_VALUE
    

    Each of the above instructions is executed with GIL lock hold and STORE_SUBSCR instruction adds/updates the key+value pair in a dictionary. So you see that dictionary update is atomic and hence thread safe.

提交回复
热议问题