python--锁

python锁的种类

threading.Lock()--互斥锁

threading.RLock--可重入锁

可重入锁(Reentrant Lock,简称 RLock) 是一种特殊类型的锁,允许同一个线程多次获取同一个锁而不会造成死锁。

获取和释放的方式

互斥锁

1. acquire()获取锁、release()释放锁
复制代码
from log import *

import threading
import time

# 共享资源
counter = 0
lock = threading.Lock()

def increment():
    global counter
    lock.acquire()
    try:
        counter += 1
        info("CUrrent thread: {}, Counter: {}".format(threading.current_thread().name, counter))
    finally:
        # 释放锁
        lock.release()

# 创建10个线程
threads = []
for _ in range(10):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

# 等待所有线程完成
for t in threads:
    t.join()
2. with 自动获取和释放锁
复制代码
from log import *

import threading
import time

counter = 0
lock = threading.Lock()

def increment():
    global counter
    # 使用 with 语句自动管理锁的获取和释放
    with lock:
        counter += 1
        info("Currrent thread: {0}, counter: {1}".format(threading.current_thread().name, counter))

# 创建10个线程
threads = []
for _ in range(10):
    t = threading.Thread(target=increment)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

可重入锁

同Lock。

复制代码
from log import *

import threading
import time

rlock = threading.RLock()  # 可重入锁

def using_rlock():
    """使用可重入锁实现更灵活的控制"""
    print("进入 with 块")
    
    with rlock:
        print("第一次获取锁")
        
        # 在 with 块内再次获取锁
        print("准备再次获取锁(嵌套)")
        with rlock:  # 可重入锁允许这样做
            print("第二次获取锁(嵌套)")
            time.sleep(1)
        
        print("退出嵌套 with,但仍持有锁")
        
        # 如果我们想"模拟"释放后重新获取
        # 实际上我们需要退出当前的 with 上下文
        print("需要释放锁...")
    
    # 现在锁已释放
    
    print("锁已释放,执行无锁操作...")
    time.sleep(2)
    
    # 重新获取锁
    with rlock:
        print("重新获取锁")
        time.sleep(1)
    
    print("完成")

# 测试
using_rlock()
相关推荐
蓝胖的四次元口袋几秒前
Python数据结构知识梳理
python
程序员清风1 分钟前
生产级智能体平台设计:任务编排、工具管理与运行监控
人工智能·python·aigc
木井巳6 分钟前
【记忆化搜索】最长递增子序列
java·算法·leetcode·深度优先·剪枝·推荐算法
杨杨杨大侠13 分钟前
知识库已经有了,Java 程序员还要做什么?Spring AI RAG 实战
java·openai·ai编程
高级程序源14 分钟前
django招聘网站信息爬取与分析系统79704-计算机课程设计、毕业设计
后端·python·mysql·小程序·django·flask·课程设计
Madison-No715 分钟前
基于JMeter工具的性能测试(接口)
python·jmeter·postman
伊信18 分钟前
Spring AI 基础学习与应用
java·后端
夜郎king25 分钟前
基于 Java + Playwright 实现网站自动访问与数据采集(以腾讯云开发者社区为例)
java·playwright·网页数据获取
小白快快跑哦27 分钟前
python-字符串全解(五):字符串格式化表达式以及格式化方法(2)
python·字符串格式化方法
Anastasiozzzz30 分钟前
重新定义 Agent 基建:Redis 在现代 AI 与智能体系统中的工程实践
java·人工智能·redis·ai