Delphi多线程下EventCache致NewWaitObj返回NIL的TMonitor.Wait异常问题
Delphi高并发服务EventCache组件NewWaitObj返回NIL异常问题
故障现象
运行于Windows平台、承载30个以上并发线程的Delphi多线程服务应用中,SysUtils.EventCache组件会出现运行时异常:NewWaitObj函数偶发返回NIL而非有效Event对象。NewWaitObj是TMonitor同步方法Wait的底层依赖方法,一旦获取到NIL事件对象,TMonitor.Wait将完全失效。该异常会扩散影响VCL与RTL框架内所有基于线程同步的逻辑,衍生各类多线程故障,例如TThreadedQueue.PopItem无法等待队列新元素到达,直接返回超时结果。
异常触发链路
异常核心出在NewWaitObj的原生实现逻辑,代码如下:
function NewWaitObj: Pointer; var EventItem: PEventItemHolder; begin EventItem := Pop(EventCache); if EventItem <> nil then begin Result := EventItem.Event; EventItem.Event := nil; Push(EventItemHolders, EventItem); end else Result := NewSyncWaitObj; ResetSyncWaitObj(Result); end;
从现象推导,高并发多线程场景下Pop函数的并发保护存在缺陷:当并发线程数达到阈值时,Pop函数会向两个甚至更多线程返回同一个EventItem实例,进而在NewWaitObj逻辑中触发竞态条件:
- 其中一个线程提取
EventItem.Event作为返回值,将该字段置为NIL后,把EventItem实例Push回缓存栈 - 并行竞争的线程获取到同一个EventItem实例时,其Event字段已被前一个线程清空,最终导致竞争线程中仅一个返回有效Event句柄,其余竞争线程全部返回NIL
- NIL事件句柄直接导致TMonitor.Wait无法正常工作
- 最终引发TThreadedQueue.PopItem等待失效、各类同步方法运行异常
Pop方法实现与测试观测
从现象判断,Pop方法内的线程同步逻辑在高并发场景下失效,其原生实现代码如下:
function Pop(var Stack: PEventItemHolder): PEventItemHolder; begin repeat Result := Stack; if Result = nil then Exit; until AtomicCmpExchange(Pointer(Stack), Result.Next, Result) = Result; end;
测试验证结果:
- 60个测试线程场景下,异常约10-20秒即可复现
- 30个测试线程场景下,复现难度提升,通常需要5-10分钟才会触发
- 异常一旦触发将持续存在,不会自行恢复,必须重启应用才能消除;测试观测到同步机制失效后,约每5次EventCache操作就有1次返回NIL
- 反汇编检查AtomicCmpExchange生成的机器码,仅包含单条CMPXCHG指令加若干寄存器准备指令,暂未明确根因:无法确定是否存在其他线程在寄存器准备阶段、或是CMPXCHG执行后的结果处理阶段产生干扰,破坏原子操作的正确性
当前应对方案与生产影响
目前团队正定位根因以寻找最优修复方案,初步规划的临时规避方案是替换原生NewWaitObj实现,循环调用原生接口直到返回有效对象。
该问题在开发、测试、生产环境中均稳定出现:生产环境运行的中间件服务通常需要数小时(部分场景为数天)才会触发异常,异常出现后仅能通过重启应用恢复。
复现参考代码
相关复现测试用例已在官方质量反馈平台提交匹配issue,可参考平台公开内容获取完整测试工程,核心复现逻辑如下:
unit FormMainEventCacheBugU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Math, Vcl.StdCtrls; const MaxProducers = 60; type TFormEventCacheBug = class(TForm) BtnMaxProducers: TButton; BtnRemoveProducer: TButton; BtnAddProducer: TButton; procedure BtnMaxProducersClick(Sender: TObject); procedure BtnRemoveProducerClick(Sender: TObject); procedure BtnAddProducerClick(Sender: TObject); private { Private declarations } public { Public declarations } end; TEventEater = class(TThread) private SleepTime: Integer; SMsg, EMsg, NMsg: PChar; procedure EatEvent; protected procedure Execute; override; public constructor Create; end; var FormEventCacheBug: TFormEventCacheBug; Producers: array[1..MaxProducers] of TThread; ProdCount: Integer; implementation {$R *.dfm} procedure AddProducer; begin if ProdCount < MaxProducers then begin Inc(ProdCount); Producers[ProdCount] := TEventEater.Create; Producers[ProdCount].FreeOnTerminate := True; end; end; procedure RemoveProducer; begin if ProdCount > 0 then begin Producers[ProdCount].Terminate; Dec(ProdCount); end; end; { TEventEater } constructor TEventEater.Create; begin inherited Create(False); SleepTime := RandomRange(1, 3); end; procedure TEventEater.EatEvent; var EventHandle: Pointer; begin EventHandle := System.MonitorSupport.NewWaitObject; try if EventHandle = nil then OutputDebugString('NIL'); Sleep(SleepTime); finally if EventHandle <> nil then System.MonitorSupport.FreeWaitObject(EventHandle); end; end; procedure TEventEater.Execute; begin SMsg := PChar('S:' + GetCurrentThreadId.ToString); EMsg := PChar('E:' + GetCurrentThreadId.ToString); NMsg := PChar('NIL:' + GetCurrentThreadId.ToString); while not Terminated do begin EatEvent; Sleep(SleepTime); end; end; procedure TFormEventCacheBug.BtnAddProducerClick(Sender: TObject); begin AddProducer; end; procedure TFormEventCacheBug.BtnRemoveProducerClick(Sender: TObject); begin RemoveProducer; end; procedure TFormEventCacheBug.BtnMaxProducersClick(Sender: TObject); var i: Integer; begin for i := ProdCount + 1 to MaxProducers do AddProducer; end; end.
诚邀技术社区提供问题根因分析与可行的修复思路。
内容的提问来源于stack exchange,提问作者Miroslav Penchev
相关产品推荐
相关产品推荐

