# When multiple threads call a shared data for operation, a thread lock is required to ensure that the data is used normally """ Implementation of multi-threaded subtraction , The initial value is 100,100 Threads per thread minus 1, The final value is 0 1、 Set up sleep simulation IO Blocking 2、 No thread lock , When invoking shared data , No locking , encounter IO Blocking time , Thread switching will occur, and other threads will get the data that has not been manipulated , The final calculation result is incorrect 3、 When there is a thread lock , When invoking shared data , It's going to lock , Until the lock is released , Only other threads can use this data , The calculation result is correct . 4、 Part of the code execution with locking in multithreading is single threaded , Outside the lock is multithreading """ # Example 1、delNum1 There is no thread lock ,delNum2 There are thread locks import threading import time def delnum1(): global num1 temp1 = num1 time.sleep(0.001) # simulation IO Blocking num1 = temp1 - 1 def delnum2(): global num2 r.acquire() # Lock temp = num2 time.sleep(0.0001) # simulation IO Blocking num2 = temp - 1 r.release() # Release if __name__ == '__main__': num1 = 100 num2 = 100 t1_list = [] t2_list = [] r = threading.Lock() # Instantiate the thread lock object for i in range(100): t1 = threading.Thread(target=delnum1) t2 = threading.Thread(target=delnum2) t1.start() t2.start() t1_list.append(t1) t2_list.append(t2) for t in t1_list: t.join() for t in t2_list: t.join() print(' No thread lock execution results :{}'.format(num1)) print(' Thread lock execution result :{}'.format(num2))