当前位置: 首页 > news >正文

Python: Condition Variable Pattern

项目结构:

image

 

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Condition Variable  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/10 21:12 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : settings.py
# 项目全局配置
TOTAL_BATCH = 3  # 每个工匠生产批次
ARTISAN_COUNT = 2  # 工匠数量
PRODUCE_DELAY = 0.5  # 生产耗时
INSPECT_DELAY = 0.3  # 质检耗时
START_WAIT_DELAY = 0.2  # 启动等待

  

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Condition Variable  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/10 21:13 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : jewelry.py
import threading
from dataclasses import dataclass
from typing import List@dataclass
class Jewelry:"""珠宝实体(数据封装)数据模型"""artisan_id: intbatch: intdef __str__(self):return f"钻石#{self.artisan_id}-{self.batch}"class JewelryInventory:"""共享库存(线程安全封装)"""def __init__(self):self._box: List[Jewelry] = []self._condition = threading.Condition()@propertydef condition(self):return self._condition@propertydef stock(self):return self._box.copy()@propertydef stock_count(self):return len(self._box)def is_empty(self):return len(self._box) == 0def put(self, jewelry: Jewelry):"""放入珠宝:param jewelry::return:"""self._box.append(jewelry)def take(self) -> Jewelry:"""取出珠宝:return:"""return self._box.pop(0)

  

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Condition Variable  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/10 21:14 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : producer.py
from ConditionVariablePattern.model.jewelry import JewelryInventory, Jewelryclass ProductionService:"""生产业务"""def __init__(self, inventory: JewelryInventory):""":param inventory:"""self.inventory = inventorydef produce(self, artisan_id: int, batch: int) -> Jewelry:"""生产并放入珠宝:param artisan_id::param batch::return:"""jewelry = Jewelry(artisan_id, batch)with self.inventory.condition:self.inventory.put(jewelry)print(f"✅ 工匠放入珠宝:{jewelry} | 当前库存:{self.inventory.stock_count}")self.inventory.condition.notify()return jewelry# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Condition Variable  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/10 21:14 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : consumer.py
from ConditionVariablePattern.model.jewelry import JewelryInventoryclass InspectionService:"""质检业务"""def __init__(self, inventory: JewelryInventory):""":param inventory:"""self.inventory = inventoryself.complete_count = 0def inspect(self, total_need: int) -> bool:"""等待珠宝并质检:param total_need::return:"""with self.inventory.condition:# 等待库存非空while self.inventory.is_empty():print("🔍 珠宝箱为空,质检员等待...")self.inventory.condition.wait()# 取出并质检jewelry = self.inventory.take()self.complete_count += 1print(f"🛡️  质检员取出珠宝:{jewelry} | 当前库存:{self.inventory.stock_count}")return self.complete_count >= total_need

  

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Condition Variable  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/10 21:20 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : artisan_thread.pyimport threading
import time
from ConditionVariablePattern.config.settings import TOTAL_BATCH, PRODUCE_DELAY
from ConditionVariablePattern.service.producer import ProductionServiceclass ArtisanThread(threading.Thread):"""工匠线程"""def __init__(self, artisan_id: int, service: ProductionService):""":param artisan_id::param service:"""super().__init__()self.artisan_id = artisan_idself.service = servicedef run(self):""":return:"""for batch in range(1, TOTAL_BATCH + 1):self.service.produce(self.artisan_id, batch)time.sleep(PRODUCE_DELAY)# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述: Condition Variable  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/10 21:22 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : inspector_thread.py
import threading
import time
from ConditionVariablePattern.config.settings import INSPECT_DELAY, ARTISAN_COUNT, TOTAL_BATCH
from ConditionVariablePattern.service.consumer import InspectionServiceclass InspectorThread(threading.Thread):"""质检员线程"""def __init__(self, service: InspectionService):""":param service:"""super().__init__()self.service = serviceself.total_need = ARTISAN_COUNT * TOTAL_BATCHdef run(self):""":return:"""while True:finished = self.service.inspect(self.total_need)if finished:breaktime.sleep(INSPECT_DELAY)

  

调用:

# encoding: utf-8 
# 版权所有  2026 ©涂聚文有限公司™ ®
# 许可信息查看:言語成了邀功盡責的功臣,還需要行爲每日來值班嗎
# 描述:Condition Variable  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/10 21:19 
# User      :  geovindu
# Product   : PyCharm
# Project   : pydesginpattern
# File      : ConditionVariableBll.py
'''
ConditionVariablePattern/
├── config/             # 配置层
│   └── settings.py     # 全局配置
├── model/              # 数据模型层
│   └── jewelry.py      # 珠宝、库存实体
├── service/            # 业务逻辑层
│   ├── producer.py     # 生产业务
│   └── consumer.py     # 质检业务
├── thread/             # 线程服务层
│   ├── artisan_thread.py  # 工匠线程
│   └── inspector_thread.py # 质检员线程
└── main.py             # 程序入口
'''
import time
from ConditionVariablePattern.config.settings import START_WAIT_DELAY
from ConditionVariablePattern.model.jewelry import JewelryInventory
from ConditionVariablePattern.service.producer import ProductionService
from ConditionVariablePattern.service.consumer import InspectionService
from ConditionVariablePattern.thread.artisan_thread import ArtisanThread
from ConditionVariablePattern.thread.inspector_thread import InspectorThreadclass ConditionVariableBll(object):""""""def demo(self):""":return:"""# 1. 初始化共享资源inventory = JewelryInventory()# 2. 初始化业务服务production_service = ProductionService(inventory)inspection_service = InspectionService(inventory)# 3. 启动质检员inspector = InspectorThread(inspection_service)inspector.start()time.sleep(START_WAIT_DELAY)# 4. 启动工匠artisans = [ArtisanThread(1, production_service),ArtisanThread(2, production_service)]for t in artisans:t.start()# 5. 等待所有线程完成for t in artisans:t.join()inspector.join()print("\n🎉 所有珠宝加工、质检完成!")

  

输出:

image

 

http://www.jsqmd.com/news/791837/

相关文章:

  • LinkSwift:八大网盘直链下载终极解决方案,告别客户端束缚
  • 2025届毕业生推荐的六大降AI率神器解析与推荐
  • LinkSwift:免费网盘直链下载的完整解决方案
  • WPS-Zotero插件终极指南:5步实现科研写作效率翻倍的完整教程
  • 从LTE到5G NR:同步信号设计演进全解析,SSB为何是性能提升的关键
  • 2026淮北干洗店大测评,权威排名帮你省心选优店! - GrowthUME
  • DLSS Swapper深度解析:游戏性能优化利器实战指南
  • 5步优化DXVK配置:告别游戏卡顿与兼容性问题
  • 5.6 springboot项目配置
  • 抖音评论数据采集神器:3分钟零代码获取完整评论数据
  • NPYViewer终极指南:如何5分钟快速可视化NumPy数组数据
  • 长期使用Taotoken平台对于模型选型决策效率的实际影响
  • LinkSwift:九大网盘直链下载,告别限速烦恼
  • 从Eclipse转战IDEA?这份无缝迁移指南和习惯养成清单请收好
  • LinkSwift:免费网盘直链下载的终极指南
  • ClawTrust:基于ERC-8004与ERC-8183构建AI智能体链上声誉与任务市场
  • Win10桌面美化避坑指南:从MyDock安装到任务栏隐藏,这些细节决定成败
  • 聚合测评:2026年值得关注的15家上海及周边SEO与网站建设公司 - 速递信息
  • 告别窗口切换烦恼:PinWin让你的Windows工作流焕然一新
  • QtMqtt模块编译实战:从源码到集成的关键步骤与排错指南
  • 在Node.js服务中集成Taotoken实现稳定的大模型调用方案
  • 观察 Taotoken 账单明细如何助力项目成本分析与优化
  • 避开5G上行同步的坑:手把手调试Timing Advance相关参数(含TATimer配置)
  • 异常5.10
  • 对比不同模型在Taotoken平台上的首次Token返回延迟体感差异
  • Gradle多模块项目实战:从settings.gradle配置到自定义目录结构的完整指南
  • 保姆级教程:用A-LOAM复现LOAM算法(ROS + Velodyne实测)
  • 外贸企业必看:主流上海网站建设公司谷歌SEO与GEO能力实测解读 - 速递信息
  • 离线安装Linux软件太头疼?保姆级教程:用pkgs.org一站式搞定所有依赖包
  • 2026上海SEO公司选型测评:深度解析几家各具特色的服务商 - 速递信息