Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange C++ thread function invocation

I have the following:

   class DThread
   {
      virtual void run()=0;

    _beginthreadex(NULL,0,tfunc,this,0,&m_UIThreadID);  // class itself being passed as param to thread function...

    static unsigned int __stdcall tfunc(void* thisptr) 
        {
            static_cast<DThread*>(thisptr)->run();
            return 0;
        }

//other stuff

}

The run function is implemented in a derived class.

Why is the function that's being called in the thread being called through a cast this pointer? Is this good practise?

Can't it just be called directly?

The actual function needing to run is in the derived class.

My question is

like image 450
Tony The Lion Avatar asked Dec 29 '22 16:12

Tony The Lion


1 Answers

_beginthreadex expects a (stdcall) C style function, it cannot use a C++ member function as it has no knowledge of C++. The way to get a member function running is to pass a pointer to an object and call the member function inside that function. Such a function is often called a trampoline.

like image 100
nos Avatar answered Dec 31 '22 04:12

nos