The case of the critical section that let multiple threads enter a block of code
Published on: 2025-06-03 15:14:25
One of my colleagues in enterprise product support runs a weekly debug talk consisting of a walkthrough of a debug session. Usually, the debug session comes to a conclusion, but one week, the debug session was unsatisfyingly inconclusive. We knew that something bad was happening, but we couldn’t figure out why.
This problem gnawed at me, so I continued debugging it after the meeting was over. Here is the story.
In the original problem, we observed a failure because a critical section failed to prevent two threads from entering the same block of code. You had one job.
typedef void (CALLBACK *TRACELOGGINGCALLBACK) (TraceLoggingHProvider, PVOID); VOID DoWithTraceLoggingHandle(TRACELOGGINGCALLBACK Callback, PVOID Context) { InitializeCriticalSectionOnDemand(); EnterCriticalSection(&g_critsec); HRESULT hr = TraceLoggingRegister(g_myProvider); if (SUCCEEDED(hr)) { (*Callback)(g_myProvider, Context); TraceLoggingUnregister(g_myProvider); } LeaveCriticalSection(&g_critsec); }
The TraceLogg
... Read full article.