Usage and Efficiency of python Multithread Shared Variables

  • 2021-07-18 08:34:53
  • OfStack

python multithreading allows tasks to be executed concurrently, but sometimes variables are "unexpected" when multiple tasks are executed.


import threading,time
n=0
start=time.time()
def b1(num):
 global n
 n=n+num
 n=n-num
def b2(num):
 for i in range(1000000):
 b1(num)
t1=threading.Thread(target=b2,args=(5,))
t2=threading.Thread(target=b2,args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
end=time.time()
print(n)
print(end-start)

Implementation results:


18
0.7520430088043213

It can be seen that the variable n changes from 0 to 18, and the time is 0.75 s. The reason is that the computer system calculates n=n+num in two steps. First, the value of n+num is calculated and put into memory, and then the calculated value is assigned to n. It is this gap that causes the variable to be "unexpected".

At this time, you can use threading. Lock to lock the variables in the thread and release them after using them!


import threading,time
n=0
lock=threading.Lock()
start=time.time()
def b1(num):
 global n
 n=n+num
 n=n-num
def b2(num):
 for i in range(1000000):
  lock.acquire()# Wait to get or get permission to modify variables and occupy them 
  b1(num)
  lock.release()# Release occupied variables 
t1=threading.Thread(target=b2,args=(5,))
t2=threading.Thread(target=b2,args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
end=time.time()
print(n)
print(end-start)

Implementation results:


0
3.335190773010254

Although the value of the variable is correct, it is many times slower, the efficiency is greatly reduced, and the advantages of multithreading are not highlighted.

Therefore, try to use local variables instead of global variables in threads, which can avoid the problem of efficiency.


Related articles: