Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using Threads

Status
Not open for further replies.

nicasa

Programmer
Feb 3, 2003
54
ES

Hello All,

I am learning how to use the TThread class to create
another thread from my mainform. Essentially, I am writing
a file/folder search program that uses a recursive function
called vSearch_Folder( ....) which takes 4 parameters. I am calling
this function within the Execute method of the thread object, using
the code below:-


void __fastcall searchThread::Execute()
{
FreeOnTerminate = false;

// call recursive search function
mainform->vSearch_Folder(THREAD_FolderPath,
THREAD_SearchString,
THREAD_iSwitch,
pTHREAD_iCounter);

// free up memory for thread object
FreeOnTerminate = true;
}

I am using a flag, FreeOnTerminate, to determine when the thread
has finished execution. (ie when the recursive function has finished.)
THe value of this flag is determined in mainform by calling inline

bool bGetThreadStatus(void){return FreeOnTerminate;};

which is declared in the class derived from TThread.



Q. Is there a better way to determine when a thread finishes execution ?

Thanks,


bigSteve
 
Well, You could use som kind of WaitForSingleObject (use the help) or let the thread end the program.

Totte
 
There's TThread::WaitFor() if you want to wait for it. You can also set the thread's OnTerminate event.

TMyThread *MyThread = new TMyThread(true);
MyThread->OnTerminate = MyThreadOnTerminate;
MyThread->Resume();

void __fastcall MyThreadOnTerminate(System::TObject* Sender)
{
// this gets called when thread ends.
// called in context of main app, so can use VCL freely.
}

I haven't tried this in a while, but my guess is that this would work very nicely.

What you're doing with FreeOnTerminate seems very dangerous to me. Doesn't this free the thread when it's done if true? So if it's true, your thread might not exist anymore.

Consider using a mutex. But if you're gonna use a flag like your doing, create a public flag and use that instead of FreeOnTerminate.

ex:
volatile bool bDone;

Make sure it's volatile so that the value gets read/written out to memory every time it's accessed. Without volatile, your thread execute function could decide to keep the value in a register and other threads wouldn't know that you changed its value.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top