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()
相关推荐
Java后端的Ai之路5 小时前
【Python 教程15】-Python和Web
python
侠客行03176 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪6 小时前
深入浅出LangChain4J
java·langchain·llm
冬奇Lab6 小时前
一天一个开源项目(第15篇):MapToPoster - 用代码将城市地图转换为精美的海报设计
python·开源
老毛肚8 小时前
MyBatis体系结构与工作原理 上篇
java·mybatis
风流倜傥唐伯虎8 小时前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
二十雨辰8 小时前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码9 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚9 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂9 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言