Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Win32, MFC: Ending threads

I have a DLL which has a CWinThread based class called CWork. I create it using AfxBeginThread.

In this class I defined a procedure that will loop infinetly and perform a certain task. This procedure will be used as a thread by itself. I create it also using AfxBeginThread.

Now, when my DLL exits, I'd like to end the thread. 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(){
    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!

like image 577
dushkin Avatar asked Dec 14 '22 14:12

dushkin


1 Answers

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. Forcefully terminating a thread is almost always a misguided idea which will come back to haunt you.

like image 120
Steve Avatar answered Mar 01 '23 22:03

Steve