In today code a Python multithreaded code, because the need for multiple threads to share the same dict, encountered a confusion, is dict is thread safe, go to the inside check, found Daniel in the discussion, so the record, specifically also need me to further verify:
In Twisted's code, DICT and list are used as thread-safe, but dict and list are not thread-wide in Jython, so twisted makes thread-safe handling for the Jython environment in particular.
Last time I asked Robert Chen for this particular question, here's a quote from Robert Chen's reply to the message:
I don't know what your specific definition of "thread safety" is. Let me say it in two ways.
1, the list of any operation of the behavior should be determined, such as the following code LST = [] lst[0] = 1
The corresponding bytecode sequence executed by the Python virtual machine is:
Load_const 1 (1)
load_fast 0 (LST)
load_const 2 (0)
STORE_SUBSCR
The operation of the stored data is in the STORE_SUBSCR byte code, where it needs to be clear that the Python virtual machine's thread scheduling, or interrupt mechanism, is granular in byte code, that is, a bytecode operation can be considered atomic operation, so Store_ Subscr even in a multi-threaded environment will not be interrupted, it can be successfully completed, so the list of any operation of the behavior is determined
2, the list of the operation of the sequence of behavior may be uncertain, such as the following code:
LST = []
thread 1:
lst[0] = 1
thread 2:
lst[0] = 2
print lst[0]
The behavior of print lst[0 in thread 2 may be indeterminate. There are two kinds of possibilities:
1, thread 1 first executed "lst[0] = 1", and then interrupted, Python virtual machine switch to thread 2, execute "lst[0] = 2,print Lst[0]" two statements, then the result of printing output is naturally 2
2. Thread 2 Executes "lst[0] = 2" First, then interrupts, the Python virtual machine switches to thread 1, executes "list[0] = 1", then interrupts occur again, the Python virtual machine switches to thread 1, executes print lst[0], Then the output should be 1, from the point of view of thread 2, the result is weird.