我正在编写一个Windows调试器,所以我有通常的ContinueDebugEvent / WaitForDebugEvent循环:
while (true)
{
ContinueDebugEvent(hTargetProcessId, hTargetThreadId, lastDebugResult);
WaitForDebugEvent(&evt, INFINITE);
...
hTargetThreadId = evt.dwThreadId;
}
这很好用,但我正在添加一个功能,需要能够在调试中执行特定的线程。要做到这一点,我暂停所有我不感兴趣的线程,就像这样(为了简洁,我省略了一大堆代码 - 希望这很清楚!):
while (true)
{
if (onlyACertainThread)
{
for (int n=0; n<threadcount; n++)
if(threads[n] != certainThread)
SuspendThread(threads[n]);
}
ContinueDebugEvent(hTargetProcessId, hTargetThreadId, lastDebugResult);
WaitForDebugEvent(&evt, INFINITE);
if (onlyACertainThread)
{
for (int n=0; n<threadcount; n++)
if(threads[n] != certainThread)
ResumeThread(threads[n]);
}
...
(code to add to 'threads', update threadcount, decide if we want to restrict to a certain thread, etc)
...
hTargetThreadId = evt.dwThreadId;
}
但是,我经常从错误的线程中看到调试事件。例如:
我想要的是最后一步是“从B获取通知”。我试过调用WaitForDebugEvent(.. B.pid ..)但这不起作用。
这是预期的行为吗?
我怀疑线程暂停/恢复计数器仅在内核被调度时才被内核观察到;即,在时间片结束时。这将导致线程A继续运行,直到其当前时间片结束。任何人都可以确认/否认这个想法吗?如果是这样......我将如何解决它?我现在最好的想法是在我暂停一个帖子之后“注入”一个人工调用Sleep(0),但我真的不想这样做,除非我必须这样做!
如果没有任何区别,我运行的机器是单线程XP盒。