Thread base class
- From: "Minus" <pakosan@xxxxxxxxx>
- Date: 6 Apr 2005 08:16:38 -0700
Folks,
For a while now I have been using threads by deriving them from a
"modified" version of the <a target="_blank"
href="http://www.codeproject.com/threads/ag_thread.asp">Win32 Worker
Thread Wrapper class (by Amer Gerzic)</a> that performs the repetitive
tasks of thread creation (etc) so that all the derived class has to do
is to call StartThread() and then override a virtual method Main()
where the thread does its work.
Reading around, however, I have found that if using MFC in the
derived class, the thread should be created with AfxBeginThread(...)
rather than with CreateThread(...), which is what this class does.
So I have modified the base class and have come up with the following
(below) which seems to work fine. Since my knowledge of threads is
borderline dismal, my questions to you guys are: 1. Are there any
blatant blunders? 2. Any subtle ones? 3. What should be added to make
it more robust/useful while keeping it as simple as possible? 4. And,
have I complicated something that could be done better?
class CTHR_BaseThread
{
public:
CTHR_BaseThread()
{
m_hThread = NULL;
m_bInYourOwnTime = FALSE;
m_bRunning = FALSE;
}
// This function is used only to call the virtual function (which
must be overridden).
// In this way all non-static members can be used from within the
thread.
static UINT StaticEntryPoint( LPVOID lParam )
{
CTHR_BaseThread* pThis = static_cast<CTHR_BaseThread*>(lParam);
UINT nRet = 0;
if( pThis != NULL )
{
pThis->m_bRunning = TRUE;
nRet = pThis->ThreadMain();
pThis->m_bRunning = FALSE;
}
return nRet;
}
// Operations
public:
// Call this method from the derived class to start the thread
BOOL StartThread()
{
// Allows thread to run in case if was aborted before
m_bInYourOwnTime = FALSE;
// If the thread is already running do not start another one
if( IsThreadRunning() )
return FALSE;
m_hThread = AfxBeginThread( StaticEntryPoint, this );
if( m_hThread == NULL )
return FALSE;
return TRUE;
}
BOOL IsThreadRunning()
{
return m_bRunning;
}
void InYourOwnTime()
{
m_bInYourOwnTime = TRUE;
}
protected:
// OVERRIDE THIS METHOD IN DERIVED CLASS!!
virtual UINT ThreadMain() = 0;
// Attributes
protected:
// Thread handle
CWinThread* m_hThread;
BOOL m_bRunning;
BOOL m_bInYourOwnTime;
public:
virtual ~CTHR_BaseThread()
{
InYourOwnTime();
}
};
Thank you all and be well.
.
- Follow-Ups:
- Re: Thread base class
- From: Doug Harrison [MVP]
- Re: Thread base class
- From: Scott McPhillips [MVP]
- Re: Thread base class
- From: Minus
- Re: Thread base class
- Prev by Date: Re: DSOleFile
- Next by Date: Calculating DPI in MM_TEXT map mode
- Previous by thread: Problem while InvokeHelper....
- Next by thread: Re: Thread base class
- Index(es):
Relevant Pages
|