百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

python线程安全:使用lock或其他技术来实现

off999 2024-11-25 15:51 15 浏览 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” 的理想持续时间。

线程安全


线程安全是指算法或程序在多个线程同时执行期间能够正常运行的属性。如果代码在多线程环境中运行时具有确定性行为并生成所需的输出,则认为代码是线程安全的。

线程安全问题的发生有两个原因:

  1. 共享的可变数据:线程共享其父进程的内存,因此所有变量和数据结构都在线程之间共享。这可能会导致在处理共享的可更改数据时出现错误。
  2. 非原子操作:当涉及多个步骤的操作被上下文切换中断时,这些操作发生在多线程环境中。如果在操作期间切换线程,这可能会导致意外结果

其实这一点和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方法,但是这个方法对同一个对象多次加锁了。最后有可能死锁

如何解决死锁后面再讲

相关推荐

Python四种常用的高阶函数,你会用了吗

每天进步一点点,关注我们哦,每天分享测试技术文章本文章出自【码同学软件测试】码同学公众号:自动化软件测试码同学抖音号:小码哥聊软件测试1、什么是高阶函数把函数作为参数传入,这样的函数称为高阶函数例如:...

Python之函数进阶-函数加强(上)(python函数的作用增强代码的可读性)

一.递归函数递归是一种编程技术,其中函数调用自身以解决问题。递归函数需要有一个或多个终止条件,以防止无限递归。递归可以用于解决许多问题,例如排序、搜索、解析语法等。递归的优点是代码简洁、易于理解,并...

数据分析-一元线性回归分析Python

前面几篇介绍了数据的相关性分析,通过相关性分析可以看出变量之间的相关性程度。如果我们已经发现变量之间存在明显的相关性了,接下来就可以通过回归分析,计算出具体的相关值,然后可以用于对其他数据的预测。本篇...

python基础函数(python函数总结)

Python函数是代码复用的核心工具,掌握基础函数的使用是编程的关键。以下是Python函数的系统总结,包含内置函数和自定义函数的详细用法,以及实际应用场景。一、Python内置函数(...

python进阶100集(9)int数据类型深入分析

一、基本概念int数据类型基本上来说这里指的都是整形,下一届我们会讲解整形和浮点型的转化,以及精度问题!a=100b=a这里a是变量名,100就是int数据对象,b指向的是a指向的对象,...

Python学不会来打我(73)python常用的高阶函数汇总

python最常用的高阶函数有counter(),sorted(),map(),reduce(),filter()。很多高阶函数都是将一个基础函数作为第一个参数,将另外一个容器集合作为第二个参数,然...

python中有哪些内置函数可用于编写数值表达式?

在Python中,用于编写数值表达式的内置函数很多,它们可以帮助你处理数学运算、类型转换、数值判断等。以下是常用的内置函数(不需要导入模块)按类别归类说明:一、基础数值处理函数函数作用示例ab...

如何在Python中获取数字的绝对值?

Python有两种获取数字绝对值的方法:内置abs()函数返回绝对值。math.fabs()函数还返回浮点绝对值。abs()函数获取绝对值内置abs()函数返回绝对值,要使用该函数,只需直接调用:a...

【Python大语言模型系列】使用dify云版本开发一个智能客服机器人

这是我的第359篇原创文章。一、引言上篇文章我们介绍了如何使用dify云版本开发一个简单的工作流:【Python大语言模型系列】一文教你使用dify云版本开发一个AI工作流(完整教程)这篇文章我们将引...

Python3.11版本使用thriftpy2的问题

Python3.11于2022年10月24日发布,但目前thriftpy2在Python3.11版本下无法安装,如果有使用thriftpy2的童鞋,建议晚点再升级到最新版本。...

uwsgi的python2+3多版本共存(python多版本兼容)

一、第一种方式(virtualenv)1、首先,机器需要有python2和python3的可执行环境。确保pip和pip3命令可用。原理就是在哪个环境下安装uwsgi。uwsgi启动的时候,就用的哪个...

解释一下Python脚本中版本号声明的作用

在Python脚本中声明版本号(如__version__变量)是一种常见的元数据管理实践,在IronPython的兼容性验证机制中具有重要作用。以下是版本号声明的核心作用及实现原理:一、版本号...

除了版本号声明,还有哪些元数据可以用于Python脚本的兼容性管理

在Python脚本的兼容性管理中,除了版本号声明外,还有多种元数据可以用于增强脚本与宿主环境的交互和验证。以下是一些关键的元数据类型及其应用场景:一、环境依赖声明1.Python版本要求pyth...

今年回家没票了?不,我有高科技抢票

零基础使用抢票开源软件Py12306一年一度的抢票季就要到了,今天给大家科普一下一款软件的使用方法。软件目前是开源的,禁止用于商用。首先需要在电脑上安装python3.7,首先从官网下载对应的安装包,...

生猛!春运抢票神器成GitHub热榜第一,过年回家全靠它了

作者:车栗子发自:凹非寺量子位报道春节抢票正在如火如荼的进行,过年回家那肯定需要抢票,每年的抢票大战,都是一场硬战,没有一个好工具,怎么能上战场死锁呢。今天小编推荐一个Python抢票工具,送到...

取消回复欢迎 发表评论: