SmacL
SmacL

Reputation: 22922

Setting default thread when breaking in debug in Visual Studio, C++

I have a C++ application developed using Visual Studio which includes a thread pool, where most of the threads are sleeping most of the time. If I break when debugging, say in a modal dialog, the thread context that comes up in the debugger is invariably one of my sleeping threads. Is there any way to automatically change this to select the main process thread rather than a sleeping worker thread? This tends to be the case when the main thread isn't sitting at AfxInternalPumpMessage() So my main thread is here;

BOOL AFXAPI AfxInternalPumpMessage()
{
    _AFX_THREAD_STATE *pState = AfxGetThreadState();

    if (!::GetMessage(&(pState->m_msgCur), NULL, NULL, NULL))  <-----
    {
#ifdef _DEBUG
        TRACE(traceAppMsg, 1, "CWinThread::PumpMessage - Received WM_QUIT.\n");
            pState->m_nDisablePumpCount++; // application must die
#endif
        // Note: prevents calling message loop things in 'ExitInstance'
        // will never be decremented
        return FALSE;
    }

while my inactive thread pools are here;

        if (pThreadInfo->m_pActivity)
        {
            SetThreadPriority(pThreadInfo->m_hThread, THREAD_PRIORITY_NORMAL);
            pThreadInfo->m_pActivity->Execute();
            SetThreadPriority(pThreadInfo->m_hThread, THREAD_PRIORITY_BELOW_NORMAL);
            pThreadInfo->m_pActivity = NULL;
        }
        else
            Sleep(50);  <-----

While it is not a big thing, it is a constant time waster. I'm guessing the logic is that the debugger favours user code over other code.

Upvotes: 2

Views: 272

Answers (1)

Jack Zhai
Jack Zhai

Reputation: 6436

The thread upon which the stopping event occurs, is the thread that is displayed. This is true even in Async-Break (although that appears to be random because bps are set on all threads in that case).

Essentially, it does this:

1) Suspend all threads

2) Set breakpoints on the ip of all threads

3) When one of those bps hit, remove all bps and display that thread as selected

4) If no bp is hit (Because of deadlock), all threads are left suspended and a fake stopping event is sent (called frozen async-break). In this case, the first thread is chosen.

You could have written a macro back in the day to do this, but today, this would require an addin or other automation client since we have no macros anymore.

Upvotes: 1

Related Questions