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()}")

输出:

相关推荐
DLYSB_4 分钟前
存储运维实战:基于 Ceph Event 监听与 Python 适配器的分布式存储健康度物理声光响应架构
运维·ceph·python·报警灯
阿童木写作20 分钟前
跨境图片翻译工具多合一,批量图片视频字幕翻译加智能抠图
人工智能·python·音视频·语音识别
隐积1 小时前
3.1.7.Qt容器大家族(3):QVariant——万能盒子
开发语言·qt
阿童木写作2 小时前
Python实现Temu图片批量翻译自动化教程
运维·人工智能·python·自动化
就是一只白3 小时前
复制地理信息python版本
python
看浪的路人3 小时前
第1讲:Agent 到底是什么?和 Chatbot 有什么区别
python·ai
名字还没想好☜4 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
瓦学妹4 小时前
什么是网络索引?它是如何工作的?
大数据·网络·python·网络爬虫
天天爱吃肉82184 小时前
商用车多体动力学实战笔记|第6篇:动力传动系统(发动机、变速箱、分动器、TCS、LSD限滑差速)
大数据·人工智能·笔记·python·嵌入式硬件·汽车
初级代码游戏5 小时前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift