Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

Determine if a Windows thread is in a Critical Section or similar?

So we have an assertion engine.

What it does is it creates a assert helper thread, suspends every other thread, then pops up some interactive UI in the helper thread to talk to the user about the assertion failure. (We suspend other threads because we want a snapshot of the program state at the point the assert failed, and we don't want the other threads to advance).

This works well, most of the time.

A small percentage of the time, one of the suspended threads has held a lock -- usually the debug heap critical section -- and the assert helper thread blocks on its next allocation (which is hard to avoid doing).

I can see two ways around this. First, to do away with the in-process assertion handling (have it launch an out-of-process assertion dialog, and use IPC to communicate back and forth). It is possible this way we can manage that communication without heap allocations. Maybe.

That is a bunch of work, because it means we have to move the in-process stack-walking code out of process, etc.

The way we are trying right now is to add a watchdog thread. It notices if the assert helper thread has failed to make progress (maybe a failure for a timer message to be sent, maybe its instruction counter stops moving; irrelevant implementation detail).

When it detects this case, it tries to break the deadlock.

Our current method is to take threads at basically random, wake them up, then suspend them again, until we detect progress from the assert helper thread. This is ... haphazard, and slow.

To make picking the right thread faster, I'd like to determine if a given windows thread currently holds a critical section (and maybe other synchronization primitives). Then we can try those threads first.

So, is there a way to determine if a windows thread currently holds a CriticalSection while it is suspended?

Upvotes: 2

Views: 972

Answers (1)

Adrian McCarthy
Adrian McCarthy

Reputation: 47962

I don't think there's a documented way to tell if a thread is in a critical section, and, if there was, I don't think it would be the right approach to your problem.

But to answer the question, you can peek inside the CRITICAL_SECTION data structure and see the handle of the thread that owns it. This doesn't directly answer the question, "Is this thread inside any critical section?" but it does let you answer, "Is this thread inside this critical section?" At least until some key implementation detail of CRITICAL_SECTION changes.

For your actual problem, I'd ask what benefit your assertion engine gives that isn't better handled by attaching a debugger when an assertion fails. A debugger is external, bypassing any deadlocks, and already knows how to walk the stacks, so you don't have to re-implement that.

Upvotes: 2

Related Questions