要安全关闭未知线程,可以使用以下方法:

  1. 遍历所有活动的线程,使用MFC的CWinThread类的GetThreadHandle()函数获取线程句柄。
BOOL EnumThreadCallback(CWinThread* pThread, LPARAM lParam)
{
    HANDLE hThread = pThread->GetThreadHandle();
    // 将线程句柄保存到一个容器中,例如一个std::vector<HANDLE>
    std::vector<HANDLE>* pThreadHandles = reinterpret_cast<std::vector<HANDLE>*>(lParam);
    pThreadHandles->push_back(hThread);
    return TRUE;
}

std::vector<HANDLE> threadHandles;
POSITION pos = AfxGetThreadState()->m_threadList.GetHeadPosition();
while (pos != nullptr)
{
    CWinThread* pThread = AfxGetThreadState()->m_threadList.GetNext(pos);
    EnumThreadCallback(pThread, reinterpret_cast<LPARAM>(&threadHandles));
}
  1. 使用线程句柄调用WaitForMultipleObjects函数等待所有线程结束。
DWORD dwResult = WaitForMultipleObjects(static_cast<DWORD>(threadHandles.size()), &threadHandles[0], TRUE, INFINITE);
  1. 根据WaitForMultipleObjects的返回值,判断是否有线程还在运行。
if (dwResult == WAIT_FAILED)
{
    // 处理等待失败的情况
}
else if (dwResult >= WAIT_OBJECT_0 && dwResult < WAIT_OBJECT_0 + threadHandles.size())
{
    // 等待成功,关闭线程
    DWORD dwThreadIndex = dwResult - WAIT_OBJECT_0;
    HANDLE hThread = threadHandles[dwThreadIndex];
    CloseHandle(hThread);
}

以上代码只是一个示例,具体实现可能需要根据具体情况进行调整

MFC不使用IsThreadActive判断其中还有未知线程没关闭还在运行将未关闭的线程安全关闭

原文地址: https://www.cveoy.top/t/topic/iYsq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录