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()
相关推荐
Charlie_Byte2 小时前
用 MurmurHash + Base62 生成短链接
java·后端
星辰落满衣2 小时前
股票实时交易数据之Python、Java等多种主流语言实例代码演示通过股票数据接口
java·开发语言·python
利刃大大2 小时前
【SpringBoot】Spring IOC && DI && 五大注解 && Bean && 扫描路径 && 依赖注入
java·spring boot·spring
William_cl2 小时前
【CSDN 精品专栏】ASP.NET Razor 变量输出 @变量名:从入门到避坑,新手也能写对!
java·数据库·asp.net
尤物程序猿3 小时前
spring的监听器的几种使用方式
java·数据库·spring
老华带你飞3 小时前
学生请假管理|基于springboot 学生请假管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·后端·spring
毕设源码-钟学长3 小时前
【开题答辩全过程】以 基于java的点餐猫在线个性化点餐系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
F_D_Z3 小时前
哈希表解Two Sum问题
python·算法·leetcode·哈希表
智算菩萨3 小时前
【实战】使用讯飞星火API和Python构建一套文本摘要UI程序
开发语言·python·ui