Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create a thread using a non static method in vc++ mfc

Tags:

visual-c++

mfc

I am creating a thread using this call:

m_pThread=AfxBeginThread(read_data,(LPVOID)hSerial);

read_data is a static method in my class.

But I want to call a non static method and make a thread.

As I want to share a variable between this thread and one of my class method.

I tried taking a static variable but it gave some errors.

like image 606
abhinav Avatar asked Feb 24 '23 05:02

abhinav


2 Answers

You cannot create a thread using a non-static member of a function as the thread procedure: the reason is all non-static methods of a class have an implicit first argument, this is pointer this.

This

class foo
{
  void dosomething();
};

is actually

class foo
{
  void dosomething(foo* this);
};

Because of that, the function signature does not match the one you need for the thread procedure. You can use a static method as thread procedure and pass the this pointer to it. Here is an example:

class foo
{
  CWindThread* m_pThread;
  HANDLE hSerial;

  static UINT MyThreadProc(LPVOID pData);

  void Start();
};

void foo::Start()
{
  m_pThread=AfxBeginThread(MyThreadProc,(LPVOID)this);
}

UINT foo::MyThreadProc(LPVOID pData)
{
  foo* self = (foo*)pData;

  // now you can use self as it was this

  ReadFile(self->hSerial, ...);

  return 0;
}
like image 159
Marius Bancila Avatar answered Apr 27 '23 20:04

Marius Bancila


I won't repeat what Marius said, but will add that I use the following:

class foo
{
    CWindThread* m_pThread;
    HANDLE hSerial;

    static UINT _threadProc(LPVOID pData);
    UINT MemberThreadProc();

    void Start();
};

void foo::Start()
{
    m_pThread=AfxBeginThread(_threadProc,(LPVOID)this);
}

UINT foo::MyThreadProc(LPVOID pData)
{
    foo* self = (foo*)pData;
    //  call class instance member
    return self->MemberThreadProc();
}

UINT foo::MemberThreadProc()
{
    //  do work
    ReadFile(hSerial, ...);
    return 0;
}

I follow this pattern every time I use threads in classes in MFC apps. That way I have the convenience of having all the members like I am in the class itself.

like image 29
Daniel Mošmondor Avatar answered Apr 27 '23 20:04

Daniel Mošmondor