程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

10、 Python learning notes - thread - thread synchronization lock

編輯:Python
# 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))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved