Visual Studio 6Visual C++ 7.0Windows 2000Visual C++ 6.0Windows XPMFCIntermediateDevVisual StudioWindowsC++
Using AfxBeginThread with class member controlling function
Create worker threads with class member controlling function
Introduction
Creating a separate thread in your application in order to execute some time consuming operations is very simple. You just call AfxBeginThread()
with the appropriate parameters and that's it. But Microsoft wants the controlling function either to be a global function or to be a static class member function; which in both cases means that you don't have access to your class member variables or methods from within the controlling function. This article shows you a little trick on how to do this and keep your source OO.
Step-by-Step
- Create your project as usual, add your dialogs, controls and all the stuff.
- Create your classes for the dialogs using Class Wizard, and assign variables to your controls.
- For the class you want to implement multithreading, edit the header file adding the following code:
//controlling function header static UINT StartThread (LPVOID param); //structure for passing to the controlling function typedef struct THREADSTRUCT { CThreadDemoDlg* _this; //you can add here other parameters you might be interested on } THREADSTRUCT;
- In the implementation file for your class, add the following code:
UINT CThreadDemoDlg::StartThread (LPVOID param) { THREADSTRUCT* ts = (THREADSTRUCT*)param; //here is the time-consuming process //which interacts with your dialog AfxMessageBox ("Thread is started!"); //see the access mode to your dialog controls ts->_this->m_ctrl_progress.SetRange (0, 1000); while (ts->_this->m_ctrl_progress.GetPos () < 1000) { Sleep(500); ts->_this->m_ctrl_progress.StepIt (); } //you can also call AfxEndThread() here return 1; }
void CThreadDemoDlg::OnStart() { //call the thread on a button action or menu THREADSTRUCT *_param = new THREADSTRUCT; _param->_this = this; AfxBeginThread (StartThread, _param); }
- Now you can test your program!
Conclusion
I hope this will be helpful for you. I've been using CodeProject for a long time and this article is the first step for payback.