If your code is in a process that has multiple threads running at the same time, it may be running the code at the same time. If the result of each run is the same as that of a single thread, and the values of other variables are the same as expected, it is thread safe. In other words, the interface provided by a class or program is atomic for threads or switching between multiple threads does not lead to ambiguity in the execution result of the interface, which means that we do not need to consider synchronization. Thread safety issues are caused by both global and static variables. If each thread only has read operations for global variables and static variables, but no write operations, generally speaking, this global variable is thread-safe; If multiple threads perform read and write operations on a variable at the same time, thread synchronization is generally required, otherwise it may affect thread security.
The purpose of lock is to prevent concurrent operations when multi-threaded execution, and objects of the reference type of lock allow only one thread to operate at a time in its locked area.
lock can only lock one reference type variable, that is, lock an address
There is a difference between the results of running with and without locking:
After locking: the value of i will decrease one by one, there will be no jumps, no repeated output, until the value of 0;
No lock: the value output of i will jump, discontinuous decreasing, and may also have a -1 value output;
Reason: After adding a lock, only one thread can execute the code in the locked area at a time, and both threads are executed in order, so there will be no interrupted output. |