Mental Jetsam

By Peter Finch

Simple C++ CWinThread Example

Posted by pcfinch on September 21, 2007

Creating a background thread in MFC is pretty simple but there is a little trick. Don’t forget to create a InitInstance() virtual function as well as the Run() function. The MFC CWinThread initialization process calls InitInstance() when it first creates the thread and expects a TRUE return value. The default function returns FALSE so the thread will not start. Here is some simple code to start a background thread using MFC.


class CServiceAdapter : public CWinThread
{
public:
    CServiceAdapter();
    virtual ~CServiceAdapter();
    virtual BOOL InitInstance() ;
    virtual int Run() ;
    CString sName ;
} ;

BOOL CServiceAdapter::InitInstance()
{
    return TRUE;
}

int CServiceAdapter::Run()
{
	TRACE(_T("CServiceAdapter: Run() calledn")) ;
	return (0) ;
}

You can simply call the CreatThread() function on the object (inherited from CWinThread) but that starts the thread immediately and does not give you an opportunity to perform any initialization on the contents of the object and can sometime cause a race condition. A nice way to start the thread [I think] is to start it suspended, do some initialization and then resume it. I have set the m_bAutoDelete to false so that when the thread is finished I can still access the contents of the class to get the results, but that’s optional. Setting it to true (the default) means that when the thread terminates the object will automatically be deleted.


CServiceAdapter* adapter = new CServiceAdapter() ;
adapter->CreateThread(CREATE_SUSPENDED) ;
adapter->m_bAutoDelete = false ; // Let me delete it.
adapter->sName = _T("Test") ; // Initialize something
adapter->ResumeThread() ;

To wait for the thread to exit use one of the many Wait for Object functions like WaitForSingleObject(). If you set bAutoDelete to false don’t forget to delete the object when you done.


WaitForSingleObject(adapter->m_hThread, INFINITE) ;
delete(adapter) ;
Advertisements

4 Responses to “Simple C++ CWinThread Example”

  1. janaka said

    Very simple example – http://jnet-films.blogspot.com

  2. iresha said

    Excellent tutorial

    Have a loot at the below tutorial for a core thread tutorial without mfc
    Windows C++ Producer Consumer Threaded Example

  3. Maheswaran said

    Really a excellent and simple multi-threading example
    Thanks a lot

  4. Vlad said

    The only problem is: InitInstance() does not want to start…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: