C ++线程终止与等待窗口

时间:2011-07-01 06:11:08

标签: c++ winapi

所以,代码就像这样:

MAIN(){
/*waiting window class declaration*/
    threadinfo* oThread=new threadinfo(); //An object that will help me know when to finish the thread
    QueueUserWorkItem((LPTHREAD_START_ROUTINE)waitingWindow, (void*)mThread, WT_EXECUTELONGFUNCTION);
    function_that_takes_time();
    oThread->setTerminated(); //set member terminated to bool true
/*continue with other things*/
}
将在该线程上运行的

和waitingWindow函数

MSG msg;
hwndWaiting=CreateWindow(...) // here the window is created
while (msg.message != WM_QUIT)
    {
        if (PeekMessage(&msg, null, 0U, 0U, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else
        {
            if(oThread->isTerminated()) // isTerminated returns bool true if terminated
            {
                delete oThread;
                ExitThread(0);
            }
        }
    }
ExitThread(0);

ExitThread是删除等待窗口的好方法,并安全地删除线程? (至少我 100%肯定这样才能结束它。)

我问这个是因为这在Windows XP中运行良好,但在Windows 7上“应用程序已停止运行”时会崩溃。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

你应该彻底退出你的循环和线程,以便正确调用任何析构函数。不要使用ExitThread(),只需使用一个标志来指示何时退出循环,然后在最后退出waitingWindow函数。

答案 1 :(得分:3)

一般来说,结束线程的最佳方法是让他们“优雅地”自己完成。您可以通过设置事件来告诉线程结束,例如:

HANDLE hevent_die = CreateEvent(...);  
HANDLE hthread_something = CreateThread(...); // or _beginthread()
...

DWORD WINAPI thread_func (LPVOID param)
{
  while(working && WaitForSingleObject(hevent_die, 0)!=WAIT_OBJECT_0)
  {
    ...
  }

  return 0;
}


while (msg.message != WM_QUIT)
{
   ...

   if(WaitForSingleObject(hthread_something, 0) == WAIT_OBJECT_0)
   {
     // do things if needed
   }
}

SetEvent(hevent_die);
WaitForSingleObject(hthread_something, INFINITE);

CloseHandle(hthread_something);
CloseHandle(hevent_die);
hthread_something = 0;
hevent_die = 0;

如果你在线程函数中使用嵌套循环,那么如果他们收到事件,他们也必须结束。