开发者

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

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?


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜