Home > Backend Development > C++ > How to Create Threads for C Class Member Functions Invoked from a Vector?

How to Create Threads for C Class Member Functions Invoked from a Vector?

Patricia Arquette
Release: 2024-12-25 19:53:12
Original
846 people have browsed it

How to Create Threads for C   Class Member Functions Invoked from a Vector?

Creating Threads for Class Member Functions

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*)'"
Copy after login

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:

  1. Use a static class method:

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);
Copy after login
  1. Use a plain ordinary function:

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]);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template