Create thread is not accepting the member function

前端 未结 3 721
刺人心
刺人心 2020-12-18 13:02

I am trying to create a class for network programming. This will create a general purpose socket with thread.

But when I tried to crete the thread using createthread

3条回答
  •  感动是毒
    2020-12-18 13:55

    There's an easy way to solve the problem.

    Take a look at ThreadProc callback function:

    
        DWORD WINAPI ThreadProc(
          __in  LPVOID lpParameter
        );
    
    

    And now at CreateThread function:

    
        HANDLE WINAPI CreateThread(
          __in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes,
          __in       SIZE_T dwStackSize,
          __in       LPTHREAD_START_ROUTINE lpStartAddress,
          __in_opt   LPVOID lpParameter,
          __in       DWORD dwCreationFlags,
          __out_opt  LPDWORD lpThreadId
        );
    
    

    Use a static method as thread procedure, but call it from a member method, and pass the object pointer to it:

    
        #include 
    
        class MyClass {
         public:
          void CreateThreadForObject() {
            LPSECURITY_ATTRIBUTES security_attributes = 0;
            SIZE_T stack_size = 0;
            LPTHREAD_START_ROUTINE start_routine = &MyClass::ThreadProcForObject;
            LPVOID param = this;
            DWORD creation_flags = 0;
            LPDWORD thread_id = 0;
            CreateThread(security_attributes, stack_size, start_routine, param,
                         creation_flags, thread_id);
          }
    
         private:
          static DWORD WINAPI ThreadProcForObject(LPVOID param) {
            MyClass* instance = reinterpret_cast(param);
            if (!instance) return 1;
            // ...
            return 0;
          }
        };
    
    

    Sorry, I just don't have enough time to write a good example. But I think you understand the way.

提交回复
热议问题