简体   繁体   English

Win32,MFC:结束线程

[英]Win32, MFC: Ending threads

I have a DLL which has a CWinThread based class called CWork. 我有一个DLL,它有一个名为CWork的基于CWinThread的类。 I create it using AfxBeginThread. 我使用AfxBeginThread创建它。

In this class I defined a procedure that will loop infinetly and perform a certain task. 在这个类中,我定义了一个将infinet循环并执行某个任务的过程。 This procedure will be used as a thread by itself. 此过程将单独用作线程。 I create it also using AfxBeginThread. 我也使用AfxBeginThread创建它。

Now, when my DLL exits, I'd like to end the thread. 现在,当我的DLL退出时,我想结束线程。 This is because I have a crash on exit, and I am affraid that is the reason. 这是因为我退出时遇到了崩溃,我很担心这就是原因。

In addition, there is 另外,还有

Pseudo Code example: 伪代码示例:

class Cmain Cmain类

Cmain::Cmain(){
    pMyThread = AfxBeginThread(CWork - a CWinThread based Class);
}

 UINT HandleNextVTSConnectionCommandProc(LPVOID pParam);

class CWork

 CWork:CWork(){
   AfxBeginThread(HandleNextVTSConnectionCommandProc, this);
 }


UINT HandleNextVTSConnectionCommandProc(LPVOID pParam){

 while(true){

     dosomething();
     sleep(2000);

 }

}

My question is, what is the correct way of ending those 2 threads? 我的问题是,结束这两个线程的正确方法是什么?

Thank you! 谢谢!

In general the correct way to end a thread is to ask it to finish and then wait for it to do so. 一般来说,结束线程的正确方法是让它完成,然后等待它完成。 So on Windows you might signal an event to ask the thread to finish up then wait on the thread HANDLE. 因此,在Windows上,您可能会发出一个事件,要求线程完成,然后等待线程HANDLE。 Forcefully terminating a thread is almost always a misguided idea which will come back to haunt you. 强行终止一个线程几乎总是一个被误导的想法,它会回来困扰你。

Create an event calling CreateEvent that is initially non-signaled. 创建一个最初未发信号的调用CreateEvent的事件。 When your application terminates, signal this event ( SetEvent ) and wait for the thread to terminate ( WaitForSingleObject on the thread handle). 当您的应用程序终止时,发出此事件的信号( SetEvent )并等待线程终止(线程句柄上的WaitForSingleObject )。

Inside your thread function HandleNextVTSConnectionCommandProc replace your while(true) loop with 在你的线程函数HandleNextVTSConnectionCommandProc你的while(true)循环替换

while(WaitForSingleObject(hEvent, 0) != WAIT_OBJECT_0)

Doing the above allows you to signal the thread to terminate from your application. 执行上述操作后,您可以通知您的应用程序终止线程。 The thread terminates, when it returns from its thread proc. 当线程从其线程proc返回时,线程终止。

Set a flag instead of using while(true) to tell your thread when it should end. 设置一个标志而不是使用while(true)来告诉你的线程何时结束。 You could also use an event. 你也可以使用一个事件。

You should also wait for your thread to be complete before you exit, so you should use (in the main code, once you signal the thread to end): 您还应该在退出之前等待线程完成,因此您应该使用(在主代码中,一旦您发出线程结束信号):

WaitForSingleObject(thread_handle)

Something like this should get you started: 这样的事情应该让你开始:

HANDLE g_hThreadExitRequest = NULL;

UINT __cdecl ThreadFunction(LPVOID pParam)
{
    AllocConsole();
    HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);

    for (int i=1; true; ++i)
    {
        CStringA count;
        count.Format("%d\n", i);
        WriteFile(hCon, (LPCSTR)count, count.GetLength(), NULL, NULL);

        if (WaitForSingleObject(g_hThreadExitRequest, 1000) == WAIT_OBJECT_0)
            break;
    }

    // We can do any thread specific cleanup here.
    FreeConsole();

    return 0;
}

void Go()
{
    // Create the event we use the request the thread exit.
    g_hThreadExitRequest = CreateEvent(
                                NULL,   // LPSECURITY_ATTRIBUTES lpEventAttributes
                                TRUE,   // BOOL bManualReset
                                FALSE,  // BOOL bInitialState
                                NULL    // LPCTSTR lpName
                                );

    // We create the thread suspended so we can mess with the returned CWinThread without
    // MFC auto deleting it when the thread finishes.
    CWinThread *pThread = AfxBeginThread(
                                &ThreadFunction,        // AFX_THREADPROC pfnThreadProc
                                NULL,                   // LPVOID pParam
                                THREAD_PRIORITY_NORMAL, // int nPriority
                                0,                      // UINT nStackSize
                                CREATE_SUSPENDED ,      // DWORD dwCreateFlags
                                NULL                    // LPSECURITY_ATTRIBUTES lpSecurityAttrs
                                );

    // Turn off MFC's auto delete "feature".
    pThread->m_bAutoDelete = FALSE;

    // Start the thread running.
    pThread->ResumeThread();

    // Wait 30 seconds.
    Sleep(30*1000);

    // Signal the thread to exit and wait for it to do so.
    SetEvent(g_hThreadExitRequest);
    WaitForSingleObject(pThread->m_hThread, INFINITE);

    // Delete the CWinTread object since we turned off auto delete.
    delete pThread;

    // We're finished with the event.
    CloseHandle(g_hThreadExitRequest);
    g_hThreadExitRequest = NULL;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM