Chicko Bueno
Chicko Bueno

Reputation: 337

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?

Upvotes: 2

Views: 2837

Answers (4)

MSalters
MSalters

Reputation: 179779

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

Upvotes: 1

bdonlan
bdonlan

Reputation: 231093

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

Upvotes: 5

chrisaycock
chrisaycock

Reputation: 37930

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.

Upvotes: 0

Steve Townsend
Steve Townsend

Reputation: 54138

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

Upvotes: 0

Related Questions