In the realm of multithreading, it's common to encounter the need to invoke member functions of a class within the thread's execution. However, this task can present challenges due to the hidden "this" parameter in C class member functions.
For instance, consider the following:
class C { void *print(void *) { coutNow, let's create a vector of C instances:
vectorclasses; pthread_t t1; classes.push_back(C()); classes.push_back(C()); To create a thread that executes c.print(), you might intuitively write:
pthread_create(&t1, NULL, &c[0].print, NULL);However, this will result in an error:
cannot convert ‘void* (tree_item::*)(void*)’ to ‘void* (*)(void*)’The issue arises because pthread_create() expects a function pointer of a specific type, whereas c[0].print is a pointer to a member function with a hidden "this" parameter.
The Solution: Using a Static Class Method or a Function Pointer
To overcome this hurdle, you have two options:
Static Class Method
A static class method does not have a "this" parameter and can be called directly without an instance of the class. Here's how you could implement a static class method for the hello function:
class C { public: static void *hello(void *) { std::coutThen, you can create a thread using the static class method:
pthread_create(&t, NULL, &C::hello, NULL);Function Pointer
Another option is to use a function pointer that encapsulates the member function and provides the "this" parameter explicitly. This function pointer can then be used to create a thread.
C c; pthread_create(&t, NULL, &C::hello_helper, &c);where hello_helper is defined as:
void *hello_helper(void *context) { return ((C *)context)->hello(); }By using a static class method or a function pointer, you can safely invoke member functions of a class within a thread, avoiding the "this" parameter issue.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3