In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of "how Python threads solve the problem of shared variables". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how Python threads solve the problem of shared variables" can help you solve the problem.
Here is another way to transfer money:
Import randomimport threadingimport datetimeimport timexuewei = {'balance': 157} # amount is negative: def transfer (money): name = threading.current_thread (). GetName () print ("% s transfer% s"% (name, money)) xuewei [' balance'] + = money print ("xuewei account balance:", xuewei ['balance']) lists = [- 7, 20,-20, 7] # the amount of 4 transfers The negative number is transferred out of the account of the school committee, and the positive number is transferred in by others. # create 4 tasks to transfer the amount of lists above threads = [] for i in range (4): amount = lists [I] name= "t -" + str (I) print ("% s plan transfer% s"% (name, amount)) mythread = threading.Thread (name=name) Target=lambda: transfer (amount) threads.append (mythread) # start transfer for t in threads: t.start () # wait 3 seconds for all the above transfer tasks to be completed We are looking at the account balance time.sleep (3) print ("-" * 16) print ("Student Committee account balance:", xuewei ['balance'])
Here, four threads are started, and there is an lambda expression in each thread, which is transferred to the account of the student committee, but the final result is 185. 5. Not 157.
The following is the running result:
PS: this is just a running result. The result of multithreading is not always the same.
How to solve this problem?
According to the observation results, we first retained only the last value of amount.
OK, let's make some changes:
Import randomimport threadingimport datetimeimport timexuewei = {'balance': 157} lists = [- 7, 20,-20, 7] # the amount transferred 4 times, the negative number is the account transfer of the student committee, and the positive number is transferred by others. Def transfer (amount): name= threading.current_thread (). GetName () print ("% s transfer% s"% (name,amount)) xuewei ['balance'] + = amount print ("xuewei account balance:", xuewei [' balance']) # create 4 tasks to transfer the amount of lists above to the student committee for i in range (4): amount = lists [I] name= str (I) # mythread = threading.Thread (name=name) Target=lambda: transfer (amount) def event (): print ("% s plan transfer% s"% (name, amount)) transfer (amount) mythread = threading.Thread (name=name, target=event) mythread.start () # wait 3 seconds for all the above transfer tasks to be completed We are looking at the account balance time.sleep (3) print ("-" * 16) print ("Student Committee account balance:", xuewei ['balance'])
The student committee has added an event function here to print out the transfer plan.
From the result of the following run, the output of the event function is correct, and all the "planned transfer" amounts are as expected [- 7, 20,-20 7]. The problem is that when the transfer function is executed in multiple threads, we find that amount has been modified by multithreading competition:
The transfer amount of user 0 becomes 20
The transfer amount of user 1 becomes-20
The transfer amount of user 2 becomes 7
The transfer amount of user 3 becomes 7
That is, the amount has been modified by the later thread, but the previous thread has not finished executing.
User 0 should transfer money to-7, but the execution has not been finished. As a result, thread 1 modified the amount to 20, user 0 continued to transfer money, and the balance became 17771. Other reasoning in turn.
The variable amount has been modified by multiple threads, and this is the shared variable of the program.
How to solve it in the end?
The method is very simple: kill the shared variable directly.
Here's how to eliminate shared variables: make sharing so that each thread accesses an independent running space
So the code changes are as follows:
Import randomimport threadingimport datetimeimport timexuewei = {'balance': 157} lists = [- 7, 20,-20, 7] # the amount transferred 4 times, the negative number is the account transfer of the student committee, and the positive number is transferred by others. # Let's not rely on the amount variable def transfer (): name = threading.current_thread (). GetName () xuewei ['balance'] + = lists [name)] # get the corresponding amount print ("xuewei account balance:" Xuewei ['balance']) # create 4 tasks to transfer the amount of lists above threads = [] for i in range (4): amount = lists [I] name= str (I) print ("% s plan transfer% s"% (name, amount)) # mythread = threading.Thread (name=name, target=lambda: transfer () def event (): transfer () mythread = threading.Thread (name=name) Target=event) threads.append (mythread) # start transfer for t in threads: t.start () # wait 3 seconds for all the above transfer tasks to be completed We are looking at the account balance time.sleep (3) print ("-" * 16) print ("Student Committee account balance:", xuewei ['balance'])
The running results are as follows:
No matter how many times the above code runs, the final account of the academic committee is 157.
Another way to avoid multithreading bug this time is to use a list subscript to correspond to the thread name one by one, so that as long as the thread with the corresponding name gets a messy value.
That's all for "how Python threads solve the problem of shared variables". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.