当前位置:网站首页>菜菜的并发编程笔记 |(五)线程安全问题以及Lock解决方案
菜菜的并发编程笔记 |(五)线程安全问题以及Lock解决方案
2022-04-23 06:19:00 【猿知】
系列索引:菜菜的并发编程笔记 | Python并发编程详解(持续更新~)
一、线程安全概念介绍
二、Lock用于解决线程安全问题
第一种方式先手动获取,在执行完后手动释放,若不释放其他程序无法上锁。第二种使用起来更加简单,with
会在程序执行结束后自定释放资源。
三、代码详解
我们使用threading模块内置的Lock
方法创建一个lock对象,这里以取钱为例,只有在获取到锁以后才可以执行下面的代码。
在main函数中我们初始化一个Account对象,创建两个线程ta和tb,让两个线程都开始执行,第一个线程正常执行,第二个线程只有等第一个线程执行完后才能获得锁。如果这段代码不加锁,两个线程同时执行就会造成余额为负数。
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)
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来解决线程安全问题十分常见,下一篇文章我们来讲使用线程池
来解决该类问题,信号量机制
在线程安全中也大有作用,欢迎关注,我会持续更新~
Python进阶之并发编程篇持续更新,欢迎
点赞收藏
+关注
上一篇:菜菜的并发编程笔记 |(四)Python实战生产者-消费者模式多线程爬虫
下一篇:菜菜的并发编程笔记 |(六)如何使用线程池改造爬虫程序详解
本人水平有限,文章中不足之处欢迎下方评论区批评指正~如果感觉对你有帮助,点个赞 支持一下吧 ~
不定期分享 有趣、有料、有营养内容,欢迎 订阅关注 我的博客 ,期待在这与你相遇 ~
版权声明
本文为[猿知]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Magic_Zsir/article/details/122672798
边栏推荐
猜你喜欢
随机推荐
Swin transformer to onnx
关于'enum'枚举类型以及结构体的问题。
学习笔记7-深度神经网络优化
javscript获取文件真实后缀名
安装tui-editor失败,快速解决方案
Urban emergency management - urban emergency communication command and dispatching system
Wireless communication system for large-scale sports events
推导式与正则式
可视化之路(十一)matplotlib颜色详解
南方投资大厦SDC智能通信巡更管理系统
各类日期转化的utils
Machine vision series (01) -- Overview
使用el-popconfirm和el-backtop不生效
Hanlp分词器(通过spark)
Emergency medical communication solution | mesh wireless ad hoc network system
anaconda3安装
连接orcale
Take you to travel in space, and American photography technology provides comprehensive technical support for aerospace creative applet
null和undefined的区别
Pep517 error during pycuda installation