Click to See Complete Forum and Search --> : HOWTO loop a derived CWinThread?


gknight
February 26th, 2005, 11:20 PM
Hello everyone,

I have tried to get a derived CWinThread to loop and so far have not had any luck. Here is what I have:

BOOL InterfaceDlg::OnInitDialog()
{
StartProcessThread();
}

void CEllistar_InterfaceDlg::StartProcessThread()
{
pThread = (CReaderThread*) AfxBeginThread(RUNTIME_CLASS(CReaderThread), THREAD_PRIORITY_NORMAL,NULL,0,NULL);
if (pThread)
{
m_ThreadList.Add(pThread);
pThread->SetLogWindow(this);
}
}

Inside of CReaderThread I have:

BOOL CReaderThread::InitInstance()
{
while(flag != 0)
{
// my processing code here
}

int CReaderThread::ExitInstance()
{
// TODO: perform any per-thread cleanup here
return CWinThread::ExitInstance();
}


return FALSE;
}

Can anyone spot why this code does not loop? When I trace it it enters InitInstance, but does not run any of the code inside it! :(

Andreas Masur
February 27th, 2005, 05:40 AM
[ Moved thread ]

Andreas Masur
February 27th, 2005, 05:44 AM
Can anyone spot why this code does not loop? When I trace it it enters InitInstance, but does not run any of the code inside it! :(
Well...pointing out the obvious...'flag' might be 0... ;)

What kind of type is it? Where does it get set?

MikeAThon
February 28th, 2005, 03:36 PM
At a more fundamental level, it's generally unwise to "loop forever" in a thread based on CWinThread. The reason is that CWinThread threads are UI threads, and "looping forever" will completely block the thread's message loop and defeat the ability to run a UI in the thread. For example, in the code you posted, it generally will not be possible to reach the ExitInstance code (but it's hard to tell since the braces in your pseudo-code do not line up).

If you really want to "loop forever", then use a pure worker thread.

Mike

gknight
February 28th, 2005, 08:30 PM
Do you have an example of a pure worker thread? I havent found an example on this site.

MikeAThon
February 28th, 2005, 09:07 PM
Threads
How to create a worker thread? http://www.codeguru.com/forum/showthread.php?t=312452
How to end a thread? http://www.codeguru.com/forum/showthread.php?t=305166
How to use member functions as thread functions?http://www.codeguru.com/forum/showthread.php?t=312453
How to access UI elements from a thread in MFC? http://www.codeguru.com/forum/showthread.php?t=312454

Mike