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

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

off999 2024-11-25 15:51 28 浏览 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方法,但是这个方法对同一个对象多次加锁了。最后有可能死锁

如何解决死锁后面再讲

相关推荐

分区合并到c盘(磁盘分区合并到c盘)

一、选择我的电脑并点击右键,选择管理菜单。二、选择储存——磁盘管理。三、以将新加卷g盘合并到c盘为例:选择G盘并单击右键呼出菜单,在菜单中选择删除卷菜单。四、点击“是”。点击c盘并单击右键。选择扩展卷...

下载万能钥匙自动连接wifi密码
  • 下载万能钥匙自动连接wifi密码
  • 下载万能钥匙自动连接wifi密码
  • 下载万能钥匙自动连接wifi密码
  • 下载万能钥匙自动连接wifi密码
免费ip转换器(ip转换器是干什么用的)

深度IP转换器软件由广州候胜科技有限公司开发的一款国内IP地址转换器软件深度IP转换器是一款动态IP和静态IP结合的IP地址修改软件,拥有全国城市节点固定IP线路5000加高速服务器IP,属于高匿名8...

笔记本键盘键位图(笔记本键盘键位图怎么看)

在笔记本的键盘左下角有个Fn键,这个键可能很多人都不知道有什么用可能也很少会用到他,就这么被忽略了。而这个Fn键就是笔记本用来开启F1到F12功能的键,有些笔记本是按住Fn键在F1到F12就能发挥他们...

如何消除手机自动出现的广告

方法一:采用关闭手机联网功能  大家都知道手机弹出广告是在手机使用联网功能下发生的,那么可以采用对手机软件联网功能的限制,从而达到屏蔽手机广告的目的,找到手机自带的“网络助手”字样的软件打开后进入到“...

免费wifi上网(怎样打开免费wifi上网)

免费wifi并非完全真实存在。免费wifi虽然在许多公共场所提供,但并非完全免费。通常情况下,提供免费wifi的场所会要求用户进行一些操作,如填写个人信息、观看广告或接受其他形式的付费。这些操作可能会...

本机ip查询地址定位查询(本机ip地址查询位置)

1.地理定位信息。具体的位置是可以通过ip地址查询得出来的。因此,对于当下电信诈骗或者一些网络虚拟的情况下,这样的查询方式是很重要的,也是很容易得出来信息的。只有这样,才能够在定位方面更加精准可靠一点...

wifi万能密码破解器(wifi万能密码破解版)

万能钥匙主要的作用是分享与被分享的关系,你所用万能钥匙一件查询和破解的都是别人分享的密码,不是万能钥匙破解的作用,真正能破解的只是那些密码简单的,比如12345678或者豹子数比如88888888和1...

win8的稳定性(win8稳定还是win10稳定)

如果是玩游戏Win7相对win7稳定一些,能兼容大部分的游戏。其它的应该各有千秋,具体上可以从如下几点了解:1、Win8相对Win7开机更快,内存管理更高效,HTML5支持更好,兼容暂时落后。2、Wi...

怎么切任务管理器(任务管理)

任务管理器切换方法如下1.先按WIN+X,再按T,即可呼出任务管理器2.同时按Ctrl+Shift+Esc,即可呼出任务管理器。3.同时按Ctrl+Alt+Del,在跳转的界面里...

windows激活无法连接到组织网络

1、在桌面新建一个文本文档,把代码复制进去2、点击文件选择“另存为”,在弹出的界面中,将保存位置选择在桌面,保存类型改为所有文件,文件名改为.bat格式的文件,然后点击“保存”按钮; 3、右...

企业邮箱注册申请流程(企业邮箱怎么注册申请)
企业邮箱注册申请流程(企业邮箱怎么注册申请)

点击进入官网,进入邮箱后,点击下方的企业邮箱,开通邮箱有两个版本,一个是免费版,一个是专业版,这边点击免费版的立即开通,弹出的界面,输入账号、密码以及手机号码,输入验证码。扩展知识:企业邮箱特点1、便于管理企业可以自行设定管理员来分配和管理...

2026-01-14 13:43 off999

window截图快捷键(windows自带截屏的方法)
window截图快捷键(windows自带截屏的方法)

1、按Prtsc键截图这样获取的是整个电脑屏幕的内容,按Prtsc键后,可以直接打开画图工具,接粘贴使用。也可以粘贴在QQ聊天框或者Word文档中,之后再选择保存即可。2、按Ctrl+Prtsc键截图截屏获得的内容也是整个电脑屏幕,与上面的...

2026-01-14 13:15 off999

win10一定要创建账户吗(win10需要创建microsoft账户吗)

win10系统安装不需要申请微软账号。如果是在安装win10的过程中,则使用本地账户登录,从安装主要步骤完成之后进入后续设置阶段开始,步骤如下:1、首先就是要输入产品密钥,或者点击左下角“以后再说”。...

win10显示已禁用输入法(w10系统已禁用输入法)

在使用win10的过程中,有时候利用第三方软件过度优化开机启动项目就容易导致win10无法打开输入法问题,这个情况是由于ctfmon程序无法正常启动所致,一般表现在电脑桌面右下角显示已禁用ime的提示...

取消回复欢迎 发表评论: