Click here to Skip to main content
Licence CPOL
First Posted 18 Jun 2002
Views 185,863
Bookmarked 22 times

Using AfxBeginThread with class member controlling function

By | 19 Jun 2002 | Article
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

  1. Create your project as usual, add your dialogs, controls and all the stuff.
  2. Create your classes for the dialogs using Class Wizard, and assign variables to your controls.
  3. 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;
  4. 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);
    }
  5. 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Enis

Software Developer (Senior)

Romania Romania

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 PinmemberPanic2k317:57 18 Sep '09  
GeneralTHREADSTRUCT Not Needed PinmemberJonathan Wood4:33 4 Feb '09  
GeneralDon't use this "trick" PinmemberRoland_W11:01 5 Nov '08  
GeneralGreat trick, thanks!! Pinmemberphilbnt22:04 5 May '08  
QuestionMulti Client Server Please Help! PinmemberMauraV18:42 13 Oct '07  
Hi!
I'm trying to implement a multi-client server and when i run my code y receive an Access Violation on the ThreadProc when i call conn->Connect.Receive. The struct Conexiones is well defined? How can my ListenSocket could hear and accept new connections. This is part of my code:
 
struct Conexion *Conexiones=Conexiones=new struct Conexion [MAX_CONEXIONES];
 
void CSockDlgServer::OnAccept()
{
int i=0;
while ((im_nThreadID=Conexiones[i].Connect.m_hSocket;
 
}
UINT CSockDlgServer::ThreadProc(LPVOID _param)
{
struct Conexion * conn=(struct Conexion *) param;
char *pBuf = new char[1025];
int iBufSize=1024;
int iRecvd;
 
// recibimos el mensaje
iRecvd=conn->Connect.Receive(pBuf,iBufSize); // here is de Access Violation
if (iRecvd==SOCKET_ERROR)
{
return 1;
}
else
{
// i do some operation with a data structure
}
return 0;
}
 
Please Help Me!
QuestionUsing this method with a other class. PinmemberCVianney22:25 9 Oct '07  
GeneralThank you very much PinmemberMember #318233416:31 5 Feb '07  
GeneralHelp for OpenGL Thread Pinmembersrinin0083:59 24 Jul '06  
GeneralAlso on memory leak Pinmemberchiac18:46 2 Apr '06  
GeneralThanks Pinmemberdhammeriz7:09 12 Dec '05  
GeneralMemory leak on THREADSTRUCT Pinmembersrev2:54 21 Jun '05  
GeneralRe: Memory leak on THREADSTRUCT PinsussAnonymous2:45 19 Oct '05  
GeneralRe: Memory leak on THREADSTRUCT Pinmemberciyoung17:36 16 Feb '06  
GeneralUnhandled Exception PinsussAnonymous2:44 26 May '04  
GeneralStop Thread Pinmemberaman20065:57 6 May '04  
GeneralRe: Stop Thread PinmemberEnis6:34 6 May '04  
GeneralRe: Stop Thread Pinmemberj.v.r.7:47 25 Aug '10  
GeneralStop Thread Problem Pinmemberaman200614:52 5 May '04  
GeneralHELP PLEASE Pinmemberwin32newb17:01 3 Mar '04  
GeneralRe: HELP PLEASE PinmemberJens Winslow6:13 17 Mar '04  
GeneralRe: HELP PLEASE Pinmemberwin32newb11:02 19 Mar '04  
GeneralRe: HELP PLEASE Pinmemberjens winslow6:34 22 Mar '04  
GeneralI thought you were supposed to pass handles, not pointers to objects into threads??? Not that that seems to work for me (HELP Please!) PinmemberJens Winslow12:47 18 Jul '03  
GeneralCorrection: AfxBeginThread(MyProcc, this->GetSafeHwnd()) NOT AfxBeginThread(MyProcc, this->AfxGetSafeHwnd()) PinmemberJens Winslow12:53 18 Jul '03  
Generalusing new to declare member might work PinmemberJens Winslow5:40 21 Jul '03  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 20 Jun 2002
Article Copyright 2002 by Enis
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid