惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

有赞技术团队
有赞技术团队
小众软件
小众软件
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园_首页
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
Jina AI
Jina AI
博客园 - 【当耐特】
V
Visual Studio Blog
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
量子位
IT之家
IT之家
G
Google Developers Blog
V
V2EX
The GitHub Blog
The GitHub Blog
月光博客
月光博客
GbyAI
GbyAI

博客园 - ®Geovin Du Dream Park™

go: Functional Options Pattern go:Timing Functions Pattern python: Timing Functions Pattern go: Steady-State Pattern python: Steady-State Pattern go: Handshaking Pattern python: Handshaking Pattern go: Fail-Fast Pattern python: Fail-Fast Pattern I go: Deadline Pattern python: Deadline Pattern go: Circuit-Breaker Pattern python: Circuit-Breaker Pattern go: Bulkheads Pattern python: Bulkheads Pattern go: Push & Pull Pattern python: Push & Pull Pattern python: Publish/Subscribe Pattern II go: Publish/Subscribe Pattern python: Publish/Subscribe Pattern go: Futures & Promises Pattern python: Futures & Promises Pattern go: Worker Pool Pattern go:Pipeline Pattern python: Worker Pool Pattern python: Pipeline Pattern go: Fan-Out Pattern python: Fan-Out Pattern go: Fan-In Pattern python: Fan-In Pattern Fan-In
python: Read-Write Lock Pattern
®Geovin Du Dream Park™ · 2026-05-19 · via 博客园 - ®Geovin Du Dream Park™

项目结构:

image

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 22:06 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry.py

from dataclasses import dataclass

@dataclass
class Jewelry:
    """
    珠宝实体:仅存储数据,无任何业务逻辑
    """
    id: str
    name: str
    price: float
    stock: int
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: 读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 21:38 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : rw_lock.py
import threading

class ReadWriteLock:
    """
    企业级读写锁:读共享、写独占
    """
    def __init__(self):
        self._write_lock = threading.Lock()
        self._read_mutex = threading.Lock()
        self._read_count = 0

    def acquire_read(self):
        with self._read_mutex:
            self._read_count += 1
            if self._read_count == 1:
                self._write_lock.acquire()

    def release_read(self):
        with self._read_mutex:
            self._read_count -= 1
            if self._read_count == 0:
                self._write_lock.release()

    def acquire_write(self):
        self._write_lock.acquire()

    def release_write(self):
        self._write_lock.release()
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 21:39 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : resource.py

import threading
from ReadWriteLockPattern.core.rw_lock import ReadWriteLock

class ResourceManager:
    """
    共享资源单例管理器,保证全局唯
    """
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        """

        """
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
                    cls._instance.rw_lock = ReadWriteLock()
        return cls._instance
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 22:07 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry_service.py

import threading
from ReadWriteLockPattern.model.jewelry import Jewelry
from ReadWriteLockPattern.core.resource import ResourceManager



class JewelryService:
    """
    珠宝业务服务:读、写、查询完全分离
    """
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance._init_data()
        return cls._instance

    def get_jewelry_list(self):
        """
        并行读:只输出内容,不重复打印标题
        :param self:
        :return:
        """
        self._lock.acquire_read()
        try:
            for j in self._jewelry_list:
                print(f"ID:{j.id} | {j.name} | 价格:{j.price} | 库存:{j.stock}")
        finally:
            self._lock.release_read()

    def print_title(self):
        """
        单独打印标题,保证输出格式精准
        :param self:
        :return:
        """
        print("======= 珠宝列表 =======")

    def _init_data(self):
        self._lock = ResourceManager().rw_lock
        self._jewelry_list = [
            Jewelry("J001", "一克拉钻石项链", 59999.99, 10)
        ]

    def print_and_get(self):
        self._lock.acquire_read()
        try:
            print("======= 珠宝列表 =======")
            for j in self._jewelry_list:
                print(f"ID:{j.id} | {j.name} | 价格:{j.price} | 库存:{j.stock}")
        finally:
            self._lock.release_read()

    def update_jewelry(self, jid: str, price: float, stock: int):
        self._lock.acquire_write()
        try:
            for j in self._jewelry_list:
                if j.id == jid:
                    j.price = price
                    j.stock = stock
                    print(f"✅ 珠宝[{jid}] 更新成功")
                    break
        finally:
            self._lock.release_write()
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 22:07 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : read_task.py
import time
from ReadWriteLockPattern.service.jewelry_service import JewelryService

def read_task():
    """
     读任务
    :return:
    """
    service = JewelryService()
    service.print_title()
    service.get_jewelry_list()
    time.sleep(0.05)
# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:读写锁模式 Read-Write Lock  Pattern
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 22:08 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : write_task.py

from ReadWriteLockPattern.service.jewelry_service import JewelryService

def write_task(jid: str, price: float, stock: int):
    """
     写任务
    :param jid:
    :param price:
    :param stock:
    :return:
    """
    service = JewelryService()
    service.update_jewelry(jid, price, stock)

调用:

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2024.3.6 python 3.11
# os        : windows 10
# database  : mysql 9.0 sql server 2019, postgreSQL 17.0  Oracle 21c Neo4j
# Datetime  : 2026/5/18 22:13 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : ReadWriteLockBll.py
'''
ReadWriteLock/
├── __init__.py
├── core/
│   ├── __init__.py
│   ├── rw_lock.py
│   └── resource.py
├── model/
│   ├── __init__.py
│   └── jewelry.py
├── service/
│   ├── __init__.py
│   └── jewelry_service.py
├── task/
│   ├── __init__.py
│   ├── read_task.py
│   └── write_task.py
└── main.py
'''
import threading
from ReadWriteLockPattern.task.read_task import read_task
from ReadWriteLockPattern.task.write_task import write_task

class ReadWriteLockBll(object):
    """

    """
    def demo(self):
        """

        :return:
        """
        print("======== 高并发并行读(客户查看珠宝)========")
        threads = [threading.Thread(target=read_task) for _ in range(10)]
        for t in threads: t.start()
        for t in threads: t.join()

        print("\n======== 独占写(商家修改价格)========")
        write_task("J001", 49999.99, 8)

        print("\n======== 再次并行读 ========")
        threads2 = [threading.Thread(target=read_task) for _ in range(5)]
        for t in threads2: t.start()
        for t in threads2: t.join()

输出:

bc6c763e-cf4b-436b-b2ae-3798d4f470a6

哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)