什么叫线程安全?
线程安全是指某个函数、函数库在多线程环境中被调用时,能够正确的处理多个线程之间的共享变量,使程序功能能够正确的完成。
lock 锁能做什么?
当然是解决线程安全问题了。!!!!
本篇所用的的类库
import threading
import time
我们的代码分两段,一段是会出现问题的,一段是不会出现问题的
import threading
import time
lock = threading.Lock()
class Account:
def __init__(self, balance):
self.balance = balance
def draw(account, amount):
if account.balance >= amount:
time.sleep(0.1) # 去除lock,加上停止指定报错
print(threading.current_thread().name,
"取钱成功!!!")
account.balance -= amount
print(threading.current_thread().name,
"余额:", account.balance)
else:
print(threading.current_thread().name,
"余额不足,取钱失败!!!!")
if __name__ == '__main__':
account = Account(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()
下面的代码不会出问题,兄弟,找不同吧
import threading
import time
lock = threading.Lock()
class Account:
def __init__(self, balance):
self.balance = balance
def draw(account, amount):
with lock:
if account.balance >= amount:
time.sleep(0.1) # 去除lock,加上停止指定报错
print(threading.current_thread().name,
"取钱成功!!!")
account.balance -= amount
print(threading.current_thread().name,
"余额:", account.balance)
else:
print(threading.current_thread().name,
"余额不足,取钱失败!!!!")
if __name__ == '__main__':
account = Account(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()

博客介绍了线程安全的概念,即函数或函数库在多线程环境中能正确处理共享变量,保证程序功能正常。还提到lock锁可解决线程安全问题,代码分为会出现问题和不会出现问题的两段。
1649

被折叠的 条评论
为什么被折叠?



