代码拉取完成,页面将自动刷新
"""
被多个线程竞争的资源称之为临界资源
临界资源通常需要锁进行保护
RLock ---> Reentrant Lock (重入锁)
current_thread() ---> 获得正在执行的当前线程
"""
import time
from concurrent.futures.thread import ThreadPoolExecutor
from threading import Thread, RLock, Condition, current_thread
class Account:
def __init__(self):
self.balance = 0
self.lock = RLock()
self.condition = Condition(self.lock)
def deposit(self, money):
with self.lock:
new_balance = self.balance + money
time.sleep(0.01)
self.balance = new_balance
# 唤醒等待中的线程
self.condition.notify_all()
def withdraw(self, money):
with self.lock:
while money > self.balance:
# 让线程暂停释放掉获得的锁
self.condition.wait()
new_balance = self.balance - money
time.sleep(0.01)
self.balance = new_balance
def main():
account = Account()
pool = ThreadPoolExecutor(max_workers=16)
# threads = []
futures = []
for _ in range(100):
future = pool.submit(account.deposit, 1)
futures.append(future)
# t = Thread(target=account.deposit, args=(1, ))
# threads.append(t)
# t.start()
for future in futures:
future.result()
# for t in threads:
# t.join()
print(account.balance)
if __name__ == '__main__':
main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。