python: Mutex Pattern

项目结构:

python 复制代码
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Mutex 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/12 22:52
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : models.py
#
class Jewelry:
    """
    实体模型:职责单一
    """
    def __init__(self, name: str, stock: int):
        """
 
        :param name:
        :param stock:
        """
        self.name = name
        self.stock = stock
 

# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Mutex 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/12 22:53
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : inventory.py
import threading
from MutexPattern.core.models import Jewelry
 
#
class ThreadSafeInventory:
    """
    全局线程安全库存(单例 + 互斥锁)
    """
    _instance = None
    _lock = threading.Lock()
 
    def __new__(cls):
        """
 
        """
        with cls._lock:
            if cls._instance is None:
                cls._instance = super().__new__(cls)
                cls._instance.jewelry = Jewelry("钻石", 0)
                cls._instance.mutex = threading.Lock()
            return cls._instance
 
    def get_stock(self):
        with self.mutex:
            return self.jewelry.stock
 
    def decrease_stock(self, count: int) -> bool:
        with self.mutex:
            if self.jewelry.stock >= count:
                self.jewelry.stock -= count
                return True
            return False
 
    def increase_stock(self, count: int):
        with self.mutex:
            self.jewelry.stock += count
python 复制代码
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Mutex 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/12 22:56
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : sell_service.py
from MutexPattern.core.inventory import ThreadSafeInventory
 
class SellService:
    """
 
    """
    def __init__(self):
        self.inventory = ThreadSafeInventory()
 
    def sell(self, seller_name: str, count: int):
        success = self.inventory.decrease_stock(count)
        current = self.inventory.get_stock()
 
        if success:
            print(f"{seller_name} -> 销售{count}颗:销售成功 | 库存:{current}")
        else:
            print(f"{seller_name} -> 销售{count}颗:库存不足,无法销售 | 库存:{current}")
 
 
 
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Mutex 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/12 22:58
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : stock_service.py
from MutexPattern.core.inventory import ThreadSafeInventory
 
class StockService:
    """
 
    """
    def __init__(self):
        self.inventory = ThreadSafeInventory()
 
    def restock(self, operator: str, count: int):
        self.inventory.increase_stock(count)
        current = self.inventory.get_stock()
        print(f"{operator} -> 补货{count}颗:补货成功 | 库存:{current}")

调用:

python 复制代码
# encoding: utf-8
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Mutex 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/12 22:58
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : MutexBll.py
import threading
from MutexPattern.service.sell_service import SellService
from MutexPattern.service.stock_service import StockService
 
class MutexBll(object):
    """
 
    """
    def demo(self):
        """
 
        :return:
        """
        sell_service = SellService()
        stock_service = StockService()
 
        # 并发任务(严格按你要求的顺序逻辑)
        threads = [
            threading.Thread(target=sell_service.sell, args=("销售员A", 1)),
            threading.Thread(target=sell_service.sell, args=("销售员B", 1)),
            threading.Thread(target=sell_service.sell, args=("销售员C", 1)),
            threading.Thread(target=stock_service.restock, args=("仓  库", 2)),
            threading.Thread(target=sell_service.sell, args=("销售员D", 1)),
        ]
 
        for t in threads:
            t.start()
        for t in threads:
            t.join()
 
        print("\n=== 所有并发任务执行完成 ===")
        print(f"最终库存:{sell_service.inventory.get_stock()}")

输出:

相关推荐
程序猿乐锅11 分钟前
【从0-1学习Python | 第七篇】Python 面向对象基础
开发语言·笔记·后端·python·学习·1024程序员节
Wang's Blog13 分钟前
Java 项目实战: 交友项目 - 查询圈子个人动态:查询我的动态需求分析
java·开发语言·交友
lzqrzpt13 分钟前
太阳能控制器选型要点:电路工艺与工程适配技术解析
python·1024程序员节
凯瑟琳.奥古斯特25 分钟前
力扣1016高效解法:剪枝优化技巧
开发语言·c++·算法·leetcode·职场和发展
.Hypocritical.1 小时前
JUC + 三大设计模式(单例、工厂、代理)
设计模式·juc·1024程序员节
databook1 小时前
时间序列数据中,如何找出缺失值
python·数据分析
坤坤子吖1 小时前
C++继承:友元、静态成员、多继承与组合
开发语言·c++·笔记·学习·1024程序员节
技术小甜甜2 小时前
【Cursor】Skill 被标黄色警告,怎么改成合格的 SKILL.md
开发语言·javascript·ai编程·cursor·1024程序员节·ai agent·skills
小小龙学IT2 小时前
Python Polars 高性能数据处理引擎深度解析
开发语言·python·rust·1024程序员节
csdn_aspnet2 小时前
JavaScript 未排序数组中第 k 个最小/最大元素 (预期线性时间)
python