Memory leakage caused by afxbeginthread (zz)
The following code indicates that memory leakage occurs when a thread starts with afxbeginthread.
For (II = 0; II <1000; II ++)
{
Cwinthread * pwinthread;
Pwinthread = afxbeginthread (threadlbproc, null );
: Sleep (500 );
}
Uint threadlbproc (lpvoid pparam)
{
Return 0;
}
A typical prompt for VC output is:
Detected memory leaks!
Dumping objects->
Thrdcore. cpp (166): {782} client block at 0x00425300, subtype 0,112 bytes long.
In fact, as long as we see the memory leakage of thrdcore. cpp (166), it is basically the same reason, just like the above Code.
Solution:
Step 1)
In the thread function, remember to write afxendthread (); (corresponds to afxbeginthread, and has corresponding functions for other start threads)
Step 2)
Use: waitforsingleobject () to ensure the thread exits completely
Step 2 is relatively easy to ignore. The sleep function can only be used to ensure that the thread exits, but cannot be ensured.
I tried it again today and found that the appropriate one is:
Afxbeginthread-> createthread-> _ beginthreadex-> _ afxthreadentry
In _ afxthreadentry, The afxendthread will be called. At this time, if
Pwinthread-> m_bautodelete = true, the entire pwinthread is deleted, and pwinthread-> m_hthread is naturally not a meaningful value.
Therefore:
// Code 1:
// Remember pwinthread for later use
M_pwinthread = afxbeginthread (threadlbproc, null );
// Do not delete m_winthread automatically to ensure that pwinthread-> m_hthread is available
M_winthread-> m_bautodelete = false;
// Code 2
Waitforsingleobject (pwinthread-> m_hthread, infinite)
Delete pwinthread; // After pwinthread-> m_hthread is used, manually delete
You should use waitsingleobject (Program handle) to wait for the program to exit, instead of sleep.
In addition, does your route use the loop = false to control the exit of the route? In this case, you should add the volatile mark before the stoploop variation. Otherwise, the optimization program will change your stoploop to register variation. No matter how you change stoploop in the main program, the stoploop in the Child Program will start to be false. Your progress will be... No.
Source: http://chenlan511.blog.163.com/blog/static/17053221320109213452748