Discussion:
TTimer created in thread executes from the main thread...?
(too old to reply)
mike_k
2008-09-29 19:04:11 UTC
Permalink
My main app creates a TThread object that in turn creates a TTimer in
its (the thread's) constructor. The Execute method in the thread is
just a message handler:

clsDChannel::clsDChannel(char *caller, char *ConfigData, int *status,
bool CreateSuspended)
: TThread(CreateSuspended)
{
ChannelTimer = new TTimer(0);
ChannelTimer->OnTimer=ChanTime;
ChannelTimer->Enabled=false;
}

void clsDChannel::Execute()
{
// create TCP socket
Dsocket = new clsDSocket(ConfigData);



ChannelTimer->Enabled = true; // this timer created in
clsDChannel constructor

while (!Terminated)
Application->ProcessMessages();
}

void __fastcall clsDChannel::ChanTime(TObject *Sender)
{
Application->ProcessMessages();
}


If I breakpoint ChanTime(), it's in the main application thread. When
I breakpoint the 'while(!Terminated)' message handler loop, it's in
the child thread, as expected.

I'm having problems with this thread eating the CPU, and I don't know
if this is related or not. How would I ensure this thread class has
its own independent timer?
mike_k
2008-09-29 19:20:23 UTC
Permalink
Update, and a partial answer to my own question:

This thread is eating the CPU because of the while(!terminated) loop;
when I replaced the code with this:

while(!Terminated)
{

// Application->ProcessMessages(); // bad!

if(MsgWaitForMultipleObjects(0,NULL,FALSE,
2500,QS_ALLINPUT)==WAIT_OBJECT_0)
{
MSG msg;
while(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}

the CPU time is reasonable. The Timer question remains, though.

Loading...