Problem:
How do you create a thread for a class member function when the function is invoked from a vector of class instances?
Example Code and Error:
Consider the following code:
class c { void *print(void *) { std::cout << "Hello"; } }; std::vector<c> classes; pthread_t t1; classes.push_back(c()); classes.push_back(c()); // Attempt to create a thread for c.print() pthread_create(&t1, NULL, &c[0].print, NULL); // Error: "cannot convert 'void* (tree_item::*)(void*)' to 'void* (*)(void*)'"
Explanation:
The error occurs because C class member functions have an implicit this parameter, which is passed internally. However, pthread_create() does not handle this hidden parameter, causing a type mismatch when casting the member function to a function pointer.
Solution:
There are two approaches to this issue:
This method does not have a this parameter, as it is associated with the class itself, not an instance. Like so:
class C { public: static void *hello(void *) { std::cout << "Hello, world!" << std::endl; return 0; } static void *hello_helper(void *context) { return ((C *)context)->hello(); } }; ... C c; pthread_t t; pthread_create(&t, NULL, &C::hello_helper, &c);
This method uses a function outside the class definition, which can access the class and its members like so:
// Outside the class void c_print_wrapper(c *c_instance) { c_instance->print(); } ... c c1, c2; pthread_t t1; classes.push_back(c1); classes.push_back(c2); // Create the thread for c.print() using wrapper function pthread_create(&t1, NULL, (void *(*)(void *))c_print_wrapper, &classes[0]);
The above is the detailed content of How to Create Threads for C Class Member Functions Invoked from a Vector?. For more information, please follow other related articles on the PHP Chinese website!