我如何在同一个类(C++,MFC)中调用工作线程?

Chi*_*eno 2 c++ mfc

这是我的代码,其中包含错误:

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;
}
Run Code Online (Sandbox Code Playgroud)

错误:

error C3867: 'ClassA::threadfn': function call missing argument list; use '&ClassA::threadfn' to create a pointer to member
Run Code Online (Sandbox Code Playgroud)

使工作线程在单个类中工作的正确方法是什么?

bdo*_*lan 5

线程创建函数不了解C++类; 因此,您的线程入口点必须是静态类成员函数或非成员函数.您可以将this指针作为lpvThreadParam参数传递给CreateThread()函数,然后让静态或非成员入口点threadfn()函数通过该指针调用该函数.

如果threadfn()函数静态的,那么请确保放在&之前C1::threadfn.

这是一个简单的例子:

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);
}
Run Code Online (Sandbox Code Playgroud)