I am running a short bit of code that will occasionally (very rarely) Access Violate on the Terminate/Free of my TThread. I am running many instances of these threads but this spot seems to be the only ones that is causing problems and it only does so once every 500 or so calls.
TThreadInheritor* Base= new TThreadInheritor(1);
try {
Base->Start();
WaitForSingleObject((HANDLE)Base->Handle, 1000);
MyBaseId = Base->scanvalue;
}__finally {
Base->Terminate();
Base->Free();
}
It is being thrown in my finally. My first guess was that WaitForSingleObject was timing out in a weird way and causing the Terminate and Free to mess up, but I'm not quite sure how that would happen. I didn't change anything to do with the Terminate/Free methods when I inherited from TThread.
Anyone know what could cause those two methods to access violate after so little code?
Never free a
TThread
that is still running. The base classTThread
destructor is not safe in that regard. It does some pretty stupid things that can cause problems. ALWAYS make sure aTThread
is fully terminated before freeing it. Use theWaitFor()
method, or wait untilWaitForSingleObject()
reportsWAIT_OBJECT_0
.