Strange C ++ stream function call

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 start function is implemented in a derived class.

Why is a function called in a thread called with the cast this pointer? Is this a good practice?

Could this be called directly?

The actual function to be performed is in the derived class.

My question

+4
source share
4 answers

Most platform-level threading APIs are bare C bones and accept a simple function pointer to run in a new thread. This means that in C ++ a function must be either free or static. None of them give access to any instance of the class. A workaround for creating Statefull stream classes is to use an additional β€œpass-through” argument to invoke the creation of the stream (which is usually a pointer, which is then passed to the function executed in the new stream) and gives it a pointer to the class itself, i.e. this . A static function can then call a [virtual] element, say run() or something like that.

+2
source

_beginthreadex expects a C (stdcall) style function, it cannot use the C ++ member function because it does not know C ++. The way to start a member function is to pass a pointer to an object and call a member function inside this function. This feature is often called a trampoline.

+4
source

Stream functions are not class members. Your implementation makes them understandable for the class, so the derived function "run" will have access to the members of the class.

+3
source

The _beginthreadex function is a C function. He knows nothing about C ++. In order to access a C ++ element from a stream function, you need to execute it.

+1
source

Source: https://habr.com/ru/post/1309977/


All Articles