How do i call worker thread in a same class (C++,

2019-05-25 10:11发布

问题:

Here is my code which contains error:

void ClassA::init()
{
    HANDLE hThread;
    data thread;          // "thread" is an object of struct data

    hThread = CreateThread(NULL, 0, C1::threadfn, &thread, 0, NULL);
}

DWORD WINAPI ClassA::threadfn(LPVOID lpParam)
{   
    data *lpData = (data*)lpParam;
}

Error:

error C3867: 'ClassA::threadfn': function call missing argument list; use '&ClassA::threadfn' to create a pointer to member

What is the proper way to make the worker thread working in a single class?

回答1:

The thread creation functions are not aware of C++ classes; as such, your thread entry point must be either a static class member function, or a non-member function. You can pass in the this pointer as the lpvThreadParam parameter to the CreateThread() function, then have the static or non-member entry point function simply call the threadfn() function via that pointer.

If the threadfn() function is static, then make sure you put & before C1::threadfn.

Here's a simple example:

class MyClass {
  private:
    static DWORD WINAPI trampoline(LPVOID pSelf);
    DWORD threadBody();
  public:
    HANDLE startThread();
}

DWORD WINAPI MyClass::trampoline(LPVOID pSelf) {
  return ((MyClass)pSelf)->threadBody();
}

DWORD MyClass::threadBody() {
  // Do the actual work here
}

HANDLE MyClass::startThread() {
  return CreateThread(NULL, 0, &MyClass::trampoline, (LPVOID)this, 0, NULL);
}


回答2:

You're using MFC, according to the tags. CreateThread is the Win32 C API, you should look at CWinThread instead.



回答3:

Follow the advice in the warning error, then this should work provided the member function threadfn is static.



回答4:

What happens if you do what the error says?

CreateThread(NULL, 0, &C1::threadfn, &thread, 0, NULL);  // now passing pointer

This assumes that threadfn() is static.



标签: c++ mfc