What is the situation of python thread safety
This article mainly introduces the situation of python thread safety, the article is very detailed, has a certain reference value, interested friends must read it!
1. Visibility problems, visibility problems caused by CPU cache, so that the operation of a pair of shared variable A can not be immediately seen by thread 2, resulting in thread 2 getting the old value.
2. Atomic problem.
For example, the statement self._balance=self._balance-draw_amount is not an atomic CPU execution command. There are three CPU commands to execute this statement.
Example
Import threadingclass Account: # define constructor def _ _ init__ (self, account_no, balance): ": param account_no: account: param balance: balance" self.account_no = account_no self._balance = balance def draw (self Draw_amount): ": param draw_amount: money to withdraw: return:"if self._balance > draw_amount: print (threading.current_thread (). GetName () + 'successful withdrawal from' + self.account_no +" The amount withdrew from the account is: "+ str (draw_amount) +"\ n ") self._balance = self._balance-draw_amount print ('account balance is' Self._balance) else: print (threading.current_thread (). GetName () + 'from' + self.account_no + "failed to withdraw money\ n") # two threads simultaneously send and withdraw money account = Account ('account one', 2000) threading.Thread (target=account.draw, name=' thread 1', args= (800,)). Start () threading.Thread (target=account.draw, name=' thread 2', args= (800,)). Start () threading.Thread (target=account.draw) Name=' thread 3', args= (800,). Start () these are all the contents of the article "what's wrong with Python thread safety?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!