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

后端 未结 2 1316
执笔经年
执笔经年 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: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);
    }
    

提交回复
热议问题