basic programming python: python multithreading and efficient use of shared variables method

Today small for everyone to share a python multithreading and efficient method to use shared variables, have a good reference value, we want to help. Come and see, to follow the small series together
python multithreading can make the tasks are executed concurrently, but sometimes when performing multiple tasks, a variable appears "accidental."

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)

Results of the:

18
0.7520430088043213

Visible variable n becomes 0 from 18, when 0.75 s is used, because the computer system calculates the similarity n = n + num is calculated in two steps, the first n + num calculated value into the memory and then calculated value assigned to n, it is this gap led to the emergence of the variable "accident."

This can be used when threading.Lock to lock the thread variable, used up and release!

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()#等待获取或获取修改变量的权限,并霸占它们
  b1(num)
  lock.release()#释放霸占的变量
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)

Results of the:

0
3.335190773010254

Although the value of the variable is correct, but a lot slower times, efficiency is greatly discounted, multi-threaded advantage did not stand out.

So try to use local variables instead of global variables in the thread, to avoid the problem of efficiency.
In fact, there is not only technical, more technical stuff than those, for example, how to make a fine programmer, rather than "Cock wire"

Programmer itself is a noble presence, ah, is not it?
Content on more than how many, and finally to recommend a good reputation

No. [programmers] public universities, there are a lot of old-timers learning skills, learning experience, interview skills, workplace experience and other share, more

We carefully prepared the zero-based introductory information, information on actual projects, the timing has to explain the Python programmer technology every day, share some learning

Methods and need to pay attention to small details, you are welcome to join, the future, beyond coding, there you have me do with a person not

Silly, a lot of money, live a long happy programmer now!Here Insert Picture Description

Published 81 original articles · won praise 18 · views 70000 +

Guess you like

Origin blog.csdn.net/chengxun02/article/details/105205534