微慑信息网

python 线程安全测试threading.lock()

抄的视频代码做的测试,代码如下?

#coding:utf-8
import  threading
import time

lock = threading.Lock()
class Myaccount:
    def __init__(self,balance):
        self.balance =balance

def draw(account,amount):
    if account.balance >= amount:
        #time.sleep(0.1)
        account.balance-=amount
        #print '取钱成功,余额为:',account.balance
        print threading.currentThread().name,'取钱成功,余额为::',account.balance
    else:
        print threading.currentThread().name,'取钱失败------------,余额:',account.balance


def main():

    while True:
        account = Myaccount(1000)
        ta = threading.Thread(name="ta",target=draw,args=(account,800))
        tb = threading.Thread(name= "tb",target=draw, args=(account, 800))
        ta.start()
        tb.start()

        #ta.join()
        #tb.join()

if __name__ == '__main__':
    main()

按原理将,在没设置线程安全锁时,是可能线程相互串行了,导致用户存款扣除800后,会再扣除800,于是余额为-600

但是,进行了大量测试,发现压根无法出现-600的情况。。。

不过按照视频说的,在线程中使用了timel.sleep方法,将会导致线程串行,会导致出现-600的情况:

下面为使用线程锁的代码(使用了with lock):

#coding:utf-8
import  threading
import time

lock = threading.Lock()
class Myaccount:
    def __init__(self,balance):
        self.balance =balance

def draw(account,amount):
    with lock:
        if account.balance >= amount:
            time.sleep(0.1)
            account.balance-=amount
            print threading.currentThread().name,'取钱成功,余额为::',account.balance
        else:
            print threading.currentThread().name,'取钱失败------------,余额:',account.balance


def main():

    while True:
        account = Myaccount(1000)
        ta = threading.Thread(name="ta",target=draw,args=(account,800))
        tb = threading.Thread(name= "tb",target=draw, args=(account, 800))
        ta.start()
        tb.start()

        #ta.join()
        #tb.join()

if __name__ == '__main__':
    main()

 

本文标题:python 线程安全测试threading.lock()
本文链接:
(转载请附上本文链接)
http://vulsee.com/archives/vulsee_2021/0906_14685.html
转载请附本站链接,未经允许不得转载,,谢谢:微慑信息网-VulSee.com » python 线程安全测试threading.lock()
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

微慑信息网 专注工匠精神

访问我们联系我们