try_module_get和module_put

本文详细介绍了Linux内核2.6版本中模块使用计数管理机制的优化,包括引入try_module_get()与module_put()函数替代2.4版本的宏管理方式,以及模块如何与特定设备交互以实现设备驱动的生命周期管理。重点阐述了模块管理与设备驱动在Linux内核中的应用与改进。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模块在被使用时,是不允许被卸载的。
   2.4内核中,模块自身通过 MOD_INC_USE_COUNT, MOD_DEC_USE_COUNT宏来管理自己被使用的计数。
   2.6内核提供了更健壮、灵活的模块计数管理接口 try_module_get(&module), module_put(&module)取代2.4中的模块使用计数管理宏;模块的使用计数不必由自身管理,而且在管理模块使用计数时考虑到 SMP与PREEMPT机制的影响。

   int try_module_get(struct module *module); 用于增加模块使用计数;若返回为0,表示调用失败,希望使用的模块没有被加载或正在被卸载中。
   void module_put(struct module *module); 减少模块使用计数。

   try_module_get与module_put 的引入与使用与2.6内核下的设备模型密切相关。模块是用来管理硬件设备的,2.6内核为不同类型的设备定义了struct module *owner 域,用来指向管理此设备的模块。如字符设备的定义:

struct cdev
{
    struct kobject kobj;
    struct module *owner;
    struct file_operations *ops;
    struct list_head list;
    dev_t dev;
    unsigned int count;
};

    从设备使用的角度出发,当需要打开、开始使用某个设备时,使用 try_module_get(dev->owner)去增加管理此设备的 owner模块的使用计数;当关闭、不再使用此设备时,使用module_put(dev->owner)减少对管理此设备的owner模块的使用 计数。这样,当设备在使用时,管理此设备的模块就不能被卸载;只有设备不再使用时模块才能被卸载。

   2.6内核下,对于为具体设备写驱动的开发人员而言,基本无需使用 try_module_get与module_put,因为此时开发人员所写的驱动通常为支持某具体设备的owner模块,对此设备owner模块的计数 管理由内核里更底层的代码如总线驱动或是此类设备共用的核心模块来实现,从而简化了设备驱动开发。
修改问题:未解析的引用 'StrictEventBus'未解析的引用 'LotteryCoordinator'未解析的引用 'AnalysisModule'未解析的引用 'Module4'未解析的引用 'StrictEventBus'未解析的引用 'LotteryCoordinator'未解析的引用 'AnalysisModule'第二个问题,事件C号码池既是前面模块1,模块2,模块3,模块4的数据接收者,又是模块5的数据传输者,具有双重身份,它的目的是收集前面模块传递过来的数据,打包又传递给模块5.在这里没有代码反应出来。第三个问题,不要出现数据,这样会影响数据分析的真实性。# ==================== 增强版事件总线 ==================== class EnhancedEventBus(StrictEventBus): """增强版事件总线(增加模块路由功能)""" def _process(self): while True: self._route_events('module_channel') time.sleep(0.01) def _route_events(self, channel_name: str): try: while not self.channels[channel_name].empty(): event = self.channels[channel_name].get_nowait() # 新增路由逻辑 if event.get('module') == '模块3': self._handle_module3_event(event) elif event.get('module') == '模块4': self._handle_module4_event(event) else: self.channels['notification_channel'].put(event) self.channels[channel_name].task_done() except queue.Empty: pass def _handle_module3_event(self, event): """专用模块3事件处理""" processed_event = { **event, 'metadata': {'handled_by': 'module3_handler'} } self.channels['notification_channel'].put(processed_event) def _handle_module4_event(self, event): """专用模块4事件处理""" processed_event = { **event, 'metadata': {'handled_by': 'module4_handler'} } self.channels['notification_channel'].put(processed_event) # ==================== 改进版号码池 ==================== class EnhancedNumberPool(NumberPool): """增强版号码池(支持多模块处理)""" def _register_handlers(self): bus = EnhancedEventBus() bus.channels['module_channel'].put = self._process_module_data # 注册模块3处理器 bus.channels['module_channel'].put_module3 = self._process_module3_data # 注册模块4处理器 bus.channels['module_channel'].put_module4 = self._process_module4_data def _process_module3_data(self, event: dict): """处理模块3数据""" fronts = event.get('data', {}).get('front_area', []) backs = event.get('data', {}).get('back_area', []) print(f"接收模块3数据 - 前区: {fronts} 后区: {backs}") self._store_module3_data(fronts, backs) def _process_module4_data(self, event: dict): """处理模块4数据""" analysis_data = event.get('analysis_result', {}) print("接收模块4趋势分析数据:") print(json.dumps(analysis_data, indent=2)) self._store_module4_data(analysis_data) def _store_module3_data(self, fronts, backs): """存储模块3数据""" with open(self.storage_path, 'a') as f: record = { 'timestamp': time.time(), 'type': 'module3', 'data': { 'fronts': fronts, 'backs': backs } } f.write(json.dumps(record) + '\n') def _store_module4_data(self, analysis_data): """存储模块4数据""" with open(self.storage_path, 'a') as f: record = { 'timestamp': time.time(), 'type': 'module4', 'data': analysis_data } f.write(json.dumps(record) + '\n') # ==================== 模块协调器 ==================== class EnhancedLotteryCoordinator(LotteryCoordinator): """增强版协调器(支持完整模块注册)""" def __init__(self): super().__init__() self._init_module_handlers() def _init_module_handlers(self): """初始化模块专用处理器""" # 模块3事件处理器 self.modules['module3'].handler = threading.Thread( target=self._handle_module3_events, daemon=True ) self.modules['module3'].handler.start() # 模块4事件处理器 self.modules['module4'].handler = threading.Thread( target=self._handle_module4_events, daemon=True ) self.modules['module4'].handler.start() def _handle_module3_events(self): """处理模块3事件流""" bus = EnhancedEventBus() while True: try: event = bus.channels['module_channel'].get(timeout=1) if event.get('module') == '模块3': print("处理模块3事件:", event) self.pool._process_module3_data(event) except queue.Empty: continue def _handle_module4_events(self): """处理模块4事件流""" bus = EnhancedEventBus() while True: try: event = bus.channels['module_channel'].get(timeout=1) if event.get('module') == '模块4': print("处理模块4事件:", event) self.pool._process_module4_data(event) except queue.Empty: continue # ==================== 模块实现 ==================== class Module3(AnalysisModule): """增强版模块3实现""" def submit_following_analysis(self, analysis_data: dict): """提交跟随分析结果""" super().submit({ 'type': 'following_analysis', 'data': analysis_data }) class Module4(Module4): """增强版模块4实现""" def submit_trend_analysis(self, analysis_data: dict): """提交趋势分析结果""" super().submit_analysis({ 'type': 'trend_analysis', 'data': analysis_data }) # ==================== 增强版事件总线 ==================== class EnhancedEventBus(StrictEventBus): """增强版事件总线(增加模块路由功能)""" def _process(self): while True: self._route_events('module_channel') time.sleep(0.01) def _route_events(self, channel_name: str): try: while not self.channels[channel_name].empty(): event = self.channels[channel_name].get_nowait() # 新增路由逻辑 if event.get('module') == '模块3': self._handle_module3_event(event) elif event.get('module') == '模块4': self._handle_module4_event(event) else: self.channels['notification_channel'].put(event) self.channels[channel_name].task_done() except queue.Empty: pass def _handle_module3_event(self, event): """专用模块3事件处理""" processed_event = { **event, 'metadata': {'handled_by': 'module3_handler'} } self.channels['notification_channel'].put(processed_event) def _handle_module4_event(self, event): """专用模块4事件处理""" processed_event = { **event, 'metadata': {'handled_by': 'module4_handler'} } self.channels['notification_channel'].put(processed_event) # ==================== 改进版号码池 ==================== class EnhancedNumberPool(NumberPool): """增强版号码池(支持多模块处理)""" def _register_handlers(self): bus = EnhancedEventBus() bus.channels['module_channel'].put = self._process_module_data # 注册模块3处理器 bus.channels['module_channel'].put_module3 = self._process_module3_data # 注册模块4处理器 bus.channels['module_channel'].put_module4 = self._process_module4_data def _process_module3_data(self, event: dict): """处理模块3数据""" fronts = event.get('data', {}).get('front_area', []) backs = event.get('data', {}).get('back_area', []) print(f"接收模块3数据 - 前区: {fronts} 后区: {backs}") self._store_module3_data(fronts, backs) def _process_module4_data(self, event: dict): """处理模块4数据""" analysis_data = event.get('analysis_result', {}) print("接收模块4趋势分析数据:") print(json.dumps(analysis_data, indent=2)) self._store_module4_data(analysis_data) def _store_module3_data(self, fronts, backs): """存储模块3数据""" with open(self.storage_path, 'a') as f: record = { 'timestamp': time.time(), 'type': 'module3', 'data': { 'fronts': fronts, 'backs': backs } } f.write(json.dumps(record) + '\n') def _store_module4_data(self, analysis_data): """存储模块4数据""" with open(self.storage_path, 'a') as f: record = { 'timestamp': time.time(), 'type': 'module4', 'data': analysis_data } f.write(json.dumps(record) + '\n') # ==================== 模块协调器 ==================== class EnhancedLotteryCoordinator(LotteryCoordinator): """增强版协调器(支持完整模块注册)""" def __init__(self): super().__init__() self._init_module_handlers() def _init_module_handlers(self): """初始化模块专用处理器""" # 模块3事件处理器 self.modules['module3'].handler = threading.Thread( target=self._handle_module3_events, daemon=True ) self.modules['module3'].handler.start() # 模块4事件处理器 self.modules['module4'].handler = threading.Thread( target=self._handle_module4_events, daemon=True ) self.modules['module4'].handler.start() def _handle_module3_events(self): """处理模块3事件流""" bus = EnhancedEventBus() while True: try: event = bus.channels['module_channel'].get(timeout=1) if event.get('module') == '模块3': print("处理模块3事件:", event) self.pool._process_module3_data(event) except queue.Empty: continue def _handle_module4_events(self): """处理模块4事件流""" bus = EnhancedEventBus() while True: try: event = bus.channels['module_channel'].get(timeout=1) if event.get('module') == '模块4': print("处理模块4事件:", event) self.pool._process_module4_data(event) except queue.Empty: continue # ==================== 模块实现 ==================== class Module3(AnalysisModule): """增强版模块3实现""" def submit_following_analysis(self, analysis_data: dict): """提交跟随分析结果""" super().submit({ 'type': 'following_analysis', 'data': analysis_data }) class Module4(Module4): """增强版模块4实现""" def submit_trend_analysis(self, analysis_data: dict): """提交趋势分析结果""" super().submit_analysis({ 'type': 'trend_analysis', 'data': analysis_data }) # ==================== 使用示例 ==================== if __name__ == "__main__": # 初始化协调器 coordinator = EnhancedLotteryCoordinator() # 模拟模块3数据 coordinator.submit('module3', { 'front_area': [5, 12, 23], 'back_area': [3, 8] }) # 模拟模块4数据 coordinator.submit('module4', { 'trend_analysis': { 'sum': 85, 'prime_ratio': '2:3', 'odd_even': '3:2' } }) # 等待处理完成 time.sleep(2) print("\n当前存储数据:") with open("lottery_data.json") as f: print(f.read())
05-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值