Can't we use threads inside the member function of class?

后端 未结 2 1317
执笔经年
执笔经年 2020-12-22 07:05

This is mine base class

class IDialysisConnector
    {
    public:
    HANDLE threadHandle_;   
    virtual int ConnectToMachine();  //This will make socket          


        
相关标签:
2条回答
  • 2020-12-22 07:29

    A non-static member function can only be called on an object. That's why its type is pointer-to-member-function and not pointer-to-function. CreateThread expects a pointer to function, and you can't give it a pointer to member function instead.

    Some folks will advise you to make it a static member function; that's usually okay, but I'm skeptical of design changes that are made only to make implementation easier. If it's a non-static member function, then, presumably, there's a reason for it to be a non-static member function.

    You can write a function that does the appropriate call:

    void callback(void*p) {
        (IDialysisConnector*p)->ServerConnectThread();
    }
    

    and pass that as the thread function, with the address of the appropriate object as the data pointer in the call to CreateThread.

    0 讨论(0)
  • 2020-12-22 07:36

    No, CreateThread expects a plain function pointer, which is quite different from a pointer to a non-static C++ member function.

    You have to create a normal function for the function you give CreateThread. That function can act as a trampoline back to the C++ world, e.g.

    static UINT WINAPI ThreadFunc(LPVOID param)
    {
       IDialysisConnector* obj = (IDialysisConnector*)param;
       obj->ServerConnectThread(); // call the member function
                                   // to do the work in our new thread
    }
    

    Then your ConnectToMachine becomes:

    int ConnectToMachine()
    {
        DWORD dwThreadId;
        //give 'this' as the thread param to ThreadFunc
        threadHandle_=CreateThread(NULL,0, (LPTHREAD_START_ROUTINE)ThreadFunc,(LPVOID)this,0,&dwThreadId);
    }
    
    0 讨论(0)
提交回复
热议问题