Mental Jetsam

By Peter Finch

Archive for September, 2007

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
    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) ;

Posted in C++/MFC | 4 Comments »