Multithreading – how do I kill an MFC thread?

I use afxbeginthread to generate a thread, which is an infinite while loop:

UINT CMyClass::ThreadProc( LPVOID param )
{
  while (TRUE)
  {
      // do stuff
  }
  return 1;
}

How do I kill this thread in my class destructor?

I imagine

UINT CMyClass::ThreadProc( LPVOID param )
{
  while (m_bKillThread)
  {
      // do stuff
  }
  return 1;
}

Then, in the destructor, M_ Bkillthread is set to false But I still need to wait in the destructor until the thread dies

Solution

Actively kill threads:

Use the return value of afxbeginthread (cwinthread *) to get the thread handle (m_hthread), and then pass the handle to the TerminateThread Win32 API This is not a safe way to terminate a thread, so read on

Wait for the thread to complete:

Get the member m using the return value of afxbeginthread (cwinthread *)_ Hthread, and then use WaitForSingleObject (P - > m_hthread, infinite); If this function returns wait_ OBJECT_ 0, the thread completes Instead of infinite, you can also wait milliseconds before the timeout occurs In this case, wait_ Timeout will be returned

Signal to your thread, it should end:

Before making WaitForSingleObject, just set some flag that the thread should exit Then in the main loop of your thread, you will check the bool value and break the infinite loop In your destructor, you will set this flag and make a WaitForSingleObject

Better way:

If you need more control, you can use things like boost conditions

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>