python线程安全:使用lock或其他技术来实现
off999 2024-11-25 15:51 32 浏览 0 评论
Python 线程
允许您同时运行代码的各个部分,从而提高代码效率。但是,如果在不了解线程安全性的情况下将线程引入代码,则可能会遇到争用条件等问题。 可以使用锁、信号量、事件、条件和屏障等工具来解决这些问题。
Python 中的线程处理
在讨论 Python 中的线程之前,、需要知道两个相关术语:
- 并发性:系统处理多个任务的能力,允许这些任务的执行时间重叠,但不一定同时发生。
- 并行度:同时执行多个任务,这些任务同时运行以利用多个处理单元,通常是多个 CPU 内核。
Python 的线程是一个并发框架,允许您启动多个并发运行的线程,每个线程执行代码段。这可以提高应用程序的效率和响应能力。当运行多个线程时,Python 解释器会在它们之间切换,将执行控制权移交给每个线程。
import threading
import time
from concurrent.futures import ThreadPoolExecutor
def threaded_function():
for number in range(3):
print(f"Printing from {threading.current_thread().name}. {number=}")
time.sleep(0.1)
with ThreadPoolExecutor(max_workers=4, thread_name_prefix="Worker") as executor:
for _ in range(4):
executor.submit(threaded_function)- 将创建四个线程来执行函数
for _ in range(4):
executor.submit(threaded_function)- 并且每个工作线程都以“Worker”前缀命名,
thread_name_prefix="Worker"- 要运行的函数功能:循环打印分配 变量 的值 0 到 2 。
看一下结果
Printing from Worker_0. number=0
Printing from Worker_1. number=0
Printing from Worker_2. number=0
Printing from Worker_3. number=0
Printing from Worker_1. number=1Printing from Worker_2. number=1Printing from Worker_3. number=1
Printing from Worker_0. number=1
Printing from Worker_1. number=2
Printing from Worker_2. number=2
Printing from Worker_0. number=2
Printing from Worker_3. number=2属性name用于获取当前线程的名字 Worker_0 Worker_1 Worker_2 Worker_3
namethreading.current_thread()输出中的每一行都表示来自工作线程的调用,worker thread name 后面的数字显示每个线程正在执行的循环的当前迭代。每个线程轮流执行 ,并且执行以并发方式而不是顺序方式进行。
- Printing from Worker_3. number=2
发生这种情况是因为 Python 解释器执行上下文切换。这意味着 Python 会暂停当前线程的执行状态,并将控制权传递给另一个线程。
当上下文切换时,Python 会保存当前执行状态,以便稍后可以恢复。通过以特定间隔切换执行控制,多个线程可以并发执行代码。
您可以通过在 REPL 中键入以下内容来检查 Python 解释器的上下文切换间隔:
import sys
sys.getswitchinterval()0.005
输出是一个以秒为单位的数字,表示 Python 解释器的上下文切换间隔。在本例中,它是 0.005 秒或 5 毫秒
可以将 switch interval 视为 Python 解释器检查它是否应切换到另一个线程的频率
此浮点值确定分配给并发运行的 Python 线程的 “timeslices” 的理想持续时间。
线程安全
线程安全是指算法或程序在多个线程同时执行期间能够正常运行的属性。如果代码在多线程环境中运行时具有确定性行为并生成所需的输出,则认为代码是线程安全的。
线程安全问题的发生有两个原因:
- 共享的可变数据:线程共享其父进程的内存,因此所有变量和数据结构都在线程之间共享。这可能会导致在处理共享的可更改数据时出现错误。
- 非原子操作:当涉及多个步骤的操作被上下文切换中断时,这些操作发生在多线程环境中。如果在操作期间切换线程,这可能会导致意外结果
其实这一点和java中的逻辑是一样的。下面一段java代码多线程修改共享变量count
public class ThreadSyn implements Runnable{
private volatile static int count = 0;
@Override
public void run() {
synchronized(this) {
for (int i = 0; i < 5; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
} GIL 及其对线程的影响
Python 的全局解释器锁 (GIL) 是一种互斥锁,可保护对 Python 对象的访问,防止多个线程同时执行 Python 字节码。GIL 只允许一个线程在单个时间点执行
当一个操作在单个字节码指令中完成时,它是原子的。由于 GIL 一次只允许一个线程运行,因此这些原子操作不会受到其他线程的干扰。这可确保原子操作通常是线程安全的
以下一个一个Python多络程序修改同一个用户的数据,但是这个程序多次运行的结果是不一致的。
import time
from concurrent.futures import ThreadPoolExecutor
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def withdraw(self, amount):
if self.balance >= amount:
new_balance = self.balance - amount
time.sleep(0.1) # Simulate a delay
self.balance = new_balance
else:
raise ValueError("Insufficient balance")
account = BankAccount(1000)
with ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(account.withdraw, 500)
executor.submit(account.withdraw, 700)
print(f"Final account balance: {account.balance}")Final account balance: 500
但是是这个结果是不确定的,原因在于多线程的不安全性。
Python 线程锁进行互斥来保证多线程修改的正确性
import threading
import time
from concurrent.futures import ThreadPoolExecutor
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
self.account_lock = threading.Lock()
def withdraw(self, amount):
with self.account_lock:
if self.balance >= amount:
new_balance = self.balance - amount
print(f"Withdrawing {amount}...")
time.sleep(0.1) # Simulate a delay
self.balance = new_balance
else:
raise ValueError("Insufficient balance")
def deposit(self, amount):
with self.account_lock:
new_balance = self.balance + amount
print(f"Depositing {amount}...")
time.sleep(0.1) # Simulate a delay
self.balance = new_balance
account = BankAccount(1000)
with ThreadPoolExecutor(max_workers=3) as executor:
executor.submit(account.withdraw, 700)
executor.submit(account.deposit, 1000)
executor.submit(account.withdraw, 300)
print(f"Final account balance: {account.balance}")- self.account_lock = threading.Lock()创建唯一锁对象
- with self.account_lock:使用with语句自动加锁与释放
with self.account_lock:
new_balance = self.balance + amount在这种情况一如何多次重复的加锁会造成死锁
如下代码
import threading
import time
from concurrent.futures import ThreadPoolExecutor
class BankAccount:
def __init__(self):
self.balance = 0
self.lock = threading.Lock()
def deposit(self, amount):
print(
f"Thread {threading.current_thread().name} "
"waiting to acquire lock for .deposit()"
)
with self.lock:
print(
f"Thread {threading.current_thread().name} "
"acquired lock for .deposit()"
)
time.sleep(0.1)
self._update_balance(amount)
def _update_balance(self, amount):
print(
f"Thread {threading.current_thread().name} "
"waiting to acquire lock for ._update_balance()"
)
with self.lock: # This will cause a deadlock
print(
f"Thread {threading.current_thread().name} "
"acquired lock for ._update_balance()"
)
self.balance += amount
account = BankAccount()
with ThreadPoolExecutor(max_workers=3, thread_name_prefix="Worker") as executor:
for _ in range(3):
executor.submit(account.deposit, 100)
print(f"Final balance: {account.balance}")deposit加锁,它调用了_update_balance方法,但是这个方法对同一个对象多次加锁了。最后有可能死锁
如何解决死锁后面再讲
相关推荐
- 安全教育登录入口平台(安全教育登录入口平台官网)
-
122交通安全教育怎么登录:122交通网的注册方法是首先登录网址http://www.122.cn/,接着打开网页后,点击右上角的“个人登录”;其次进入邮箱注册,然后进入到注册页面,输入相关信息即可完...
- 大鱼吃小鱼经典版(大鱼吃小鱼经典版(经典版)官方版)
-
大鱼吃小鱼小鱼吃虾是于谦跟郭麒麟的《我的棒儿呢?》郭德纲说于思洋郭麒麟作诗的相声,最后郭麒麟做了一首,师傅躺在师母身上大鱼吃小鱼小鱼吃虾虾吃水水落石出师傅压师娘师娘压床床压地地动山摇。...
-
- 哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)
-
要想将ppt免费转换为pdf的话,我们建议大家可以下一个那个wps,如果你是会员的话,可以注册为会员,这样的话,在wps里面的话,就可以免费将ppt呢转换为pdfpdf之后呢,我们就可以直接使用,不需要去直接不需要去另外保存,为什么格式转...
-
2026-02-04 09:03 off999
- 电信宽带测速官网入口(电信宽带测速官网入口app)
-
这个网站看看http://www.swok.cn/pcindex.jsp1.登录中国电信网上营业厅,宽带光纤,贴心服务,宽带测速2.下载第三方软件,如360等。进行在线测速进行宽带测速时,尽...
- 植物大战僵尸95版手机下载(植物大战僵尸95 版下载)
-
1可以在应用商店或者游戏平台上下载植物大战僵尸95版手机游戏。2下载教程:打开应用商店或者游戏平台,搜索“植物大战僵尸95版”,找到游戏后点击下载按钮,等待下载完成即可安装并开始游戏。3注意:确...
- 免费下载ppt成品的网站(ppt成品免费下载的网站有哪些)
-
1、Chuangkit(chuangkit.com)直达地址:chuangkit.com2、Woodo幻灯片(woodo.cn)直达链接:woodo.cn3、OfficePlus(officeplu...
- 2025世界杯赛程表(2025世界杯在哪个国家)
-
2022年卡塔尔世界杯赛程公布,全部比赛在卡塔尔境内8座球场举行,2022年,决赛阶段球队全部确定。揭幕战于当地时间11月20日19时进行,由东道主卡塔尔对阵厄瓜多尔,决赛于当地时间12月18日...
- 下载搜狐视频电视剧(搜狐电视剧下载安装)
-
搜狐视频APP下载好的视频想要导出到手机相册里方法如下1、打开手机搜狐视频软件,进入搜狐视频后我们点击右上角的“查找”,找到自已喜欢的视频。2、在“浏览器页面搜索”窗口中,输入要下载的视频的名称,然后...
- 永久免费听歌网站(丫丫音乐网)
-
可以到《我爱音乐网》《好听音乐网》《一听音乐网》《YYMP3音乐网》还可以到《九天音乐网》永久免费听歌软件有酷狗音乐和天猫精灵,以前要跳舞经常要下载舞曲,我从QQ上找不到舞曲下载就从酷狗音乐上找,大多...
- 音乐格式转换mp3软件(音乐格式转换器免费版)
-
有两种方法:方法一在手机上操作:1、进入手机中的文件管理。2、在其中选择“音乐”,将显示出手机中的全部音乐。3、点击“全选”,选中所有音乐文件。4、点击屏幕右下方的省略号图标,在弹出菜单中选择“...
- 电子书txt下载(免费的最全的小说阅读器)
-
1.Z-library里面收录了近千万本电子书籍,需求量大。2.苦瓜书盘没有广告,不需要账号注册,使用起来非常简单,直接搜索预览下载即可。3.鸠摩搜书整体风格简洁清晰,书籍资源丰富。4.亚马逊图书书籍...
- 最好免费观看高清电影(播放免费的最好看的电影)
-
在目前的网上选择中,IMDb(互联网电影数据库)被认为是最全的电影网站之一。这个网站提供了各种类型的电影和电视节目的海量信息,包括剧情介绍、演员表、评价、评论等。其还提供了有关电影制作背后的详细信息,...
- 孤单枪手2简体中文版(孤单枪手2简体中文版官方下载)
-
要将《孤胆枪手2》游戏的征兵秘籍切换为中文,您可以按照以下步骤进行操作:首先,打开游戏设置选项,通常可以在游戏主菜单或游戏内部找到。然后,寻找语言选项或界面选项,点击进入。在语言选项中,选择中文作为游...
欢迎 你 发表评论:
- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
