Search code examples
c#c++multithreadingbackgroundworkercreatethread

Function pointers in C++


I used CreateThread function to write a class like C# BackgroundWorker in C++.My code:

BackgroundWorker.h:

class BackgroundWorker
{
    private :
        HANDLE _threadHandle;
        unsigned int _threadCallcounter;
        DWORD _threadID;
    public:
        BackgroundWorker();
        ~BackgroundWorker();
        virtual DWORD WINAPI Function(LPVOID vpPram);
}

BackgroundWorker.cpp:

#include "BackgroundWorker.h"
void BackgroundWorker::DoWork()
{
    this->_threadHandle = CreateThread(NULL,
        0,this->Function,&this->_threadCallcounter,
        0, &this->_threadID); // !!!***This part throws an error***!!!
}

Then I created another class that derived from BackgroundWorker:

ListenThread.cpp:

class ListenThread :public BackgroundWorker
{
    DWORD WINAPI Function(LPVOID vpPram)
    {
        //DO somthing...
        return 0;
    }
};

But that line gives me the following error:

non - standard syntax; use '&' to create a pointer to member


Solution

  • Your error message means you need to pass pointer to function as &Function, not Function in DoWork.

    Unfortunately fixing this won't help. CreateThread doesn't work with (non-static) member functions. A solution is to create a static method to use as the actual thread start function.

    Check this example:

    #include <Windows.h>
    #include <iostream>
    
    class BackgroundWorker
    {
    private :
        HANDLE _threadHandle;
        DWORD _threadID;
    
    public:
        static DWORD WINAPI StaticThreadStart(void * Param) {
            BackgroundWorker * This = static_cast<BackgroundWorker *>(Param);
            return This->Function();
        }
    
        virtual DWORD Function() {
            return 0;
        }
    
        void DoWork() {
            _threadHandle = CreateThread(NULL, 0, StaticThreadStart, this, 0, &_threadID);
        }
    };
    
    class ListenThread : public BackgroundWorker {
        DWORD Function() override {
            std::cout << "Working...\n";
            return 0;
        }
    };
    
    int main()
    {
        ListenThread cl;
        cl.DoWork();
    
        // Call pause to wait for new thread in this example
        system("pause");
        return 0;
    }