文章摘要
这篇文章讨论了Windows内核模式下进程和线程回调函数的最佳实践,核心要点是这些回调函数必须保持简短高效,避免进行耗时操作(如调用用户模式服务、访问注册表、阻塞或跨进程通信),也不能与其他线程同步,因为这些操作可能导致系统死锁或显著拖慢整个系统的运行速度。这些严格限制说明回调函数可能在系统持有内部锁时被调用,因此必须快速执行。
文章总结
理解规则背后的原理才能有效规避问题
微软官方文档《实现进程和线程相关回调函数的最佳实践》中明确指出: - 保持回调函数简短高效 - 避免调用用户模式服务进行验证 - 禁止注册表操作 - 禁止阻塞性调用和进程间通信(IPC) - 避免与其他线程同步以防止重入死锁
这些严格限制表明,这类回调函数(涉及进程/线程创建终止、DLL加载卸载等底层事件)必须在系统持有内部锁的情况下快速执行,任何延迟都会拖慢整个系统。
文档建议将耗时操作(如慢速API调用或阻塞性操作)通过系统工作线程异步处理。但企业支持团队经常发现,某些驱动程序虽然将工作委派给系统工作线程,却仍同步等待工作完成——这本质上仍是阻塞行为。
2020年更新的文档特别新增条款:"如果使用系统工作线程,不要等待工作完成",以堵住这个规则漏洞。这就像父母禁止孩子开电视,孩子却指使兄弟代劳——形式不同但本质相同。
作者Raymond Chen建议文档应开宗明义强调: 1. 回调函数必须快速非阻塞执行 2. 复杂操作应通过系统工作线程异步处理 3. 明确列出所有禁止的阻塞行为示例
(作者简介:Raymond Chen是拥有30年Windows开发经验的资深工程师,自2003年起运营"The Old New Thing"技术博客并出版同名著作。)
评论总结
根据评论内容,主要观点和论据总结如下:
1. 对微软文档和系统设计的批评
- 评论1指出微软内部流程僵化,员工宁愿写博客也不直接改进文档,反映系统性问题。
- "Microsoft is so broken that an employee finds it easier to write a blog post about a documentation improvement than simply making that improvement?"
- "Conway's Flaw?"
- 评论2通过同事的亲身经历,强调Windows系统逻辑混乱,需放弃“合理”的预设才能理解。
- "you make the primary mistake of thinking anything in windows makes sense"
- "once you abandon this bias, you may someday hope to get where i am"
2. 对文档设计缺陷的反思
- 评论4引用“切斯特顿围栏”概念,指出代码遵循字面规则却忽略其存在理由。
- "the code followed the wording while missing the reason the rule existed"
- "you should understand why a rule exists before trying to remove it or work around it"
- 评论6认为文档常只描述设计而不解释动机,源于作者的知识诅咒或保密需求。
- "the motivation behind design is not communicated, just the design itself"
- "the writer is too close to the project, and is struck by the curse of knowledge"
3. 对系统复杂性的隐喻与建议
- 评论5用“猴子实验”比喻规则被盲目遵守的现象,强调理解“为什么”比“怎么做”更重要。
- "there are many rules that are enforced without anyone questioning the 'why'"
- "the 'why' is often more important to know than the rule itself"
- 评论7质疑WinAPI回调机制是否应简化为消息传递。
- "How many of these winapi callbacks should have been just messages?"
- 评论8建议Windows提供内核回调的注册与性能数据,便于调试。
- "I really wish Windows had a way to show what kernel callbacks are registered and execute on each call"
- "Using that one could much more easily to debug and potentially uninstall misbehaving software"
平衡性说明:评论整体对微软文档和系统设计持批评态度,但部分评论(如评论4、6)从方法论角度提出建设性反思,评论8则给出具体改进建议。