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

Python multithread shared variable resource contention

編輯:Python

1. Resource competition :sum+=1 There are roughly three steps to execute ( Value 、 Add 1、 Write back to ), Probably just executed 2 Step cpu I switched to another thread to execute ;
2. terms of settlement :1. Use join() Method to set thread synchronization ( The efficiency is not high ),2. Lock ( It can ensure that only one thread is executing at the same time ) .

'''
Resource competition :sum+=1 There are roughly three steps to execute ( Value 、 Add 1、 Write back to ), Probably just executed 2 Step cpu I switched to another thread to execute
terms of settlement :1. Use join() Method to set thread synchronization ( The efficiency is not high ),2. Lock ( It can ensure that only one thread is executing at the same time )
'''
import threading
import time
sum=0
lock=threading.Lock()
def add_num1():
global sum
for i in range(1000000):
# lock.acquire() # Lock
sum+=1
# lock.release() # Unlock
print(f'{threading.current_thread().name} The result is {sum}')
def add_num2():
global sum
for i in range(1000000):
# lock.acquire()
sum+=1
# lock.release()
print(f'{threading.current_thread().name} The result is {sum}')
if __name__ == '__main__':
t1=threading.Thread(target=add_num1)
t2=threading.Thread(target=add_num2)
t1.start()
# Set blocking function , Set thread synchronization
t1.join()
t2.start()
print(f'Main Of sum The value is {sum}')


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