2 Star 1 Fork 15

jackfrued/review

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
example06.py 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
"""
被多个线程竞争的资源称之为临界资源
临界资源通常需要锁进行保护
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()
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/jackfrued/review.git
git@gitee.com:jackfrued/review.git
jackfrued
review
review
master

搜索帮助