Home >Backend Development >C++ >How to Correctly Create Threads for C Class Member Functions?

How to Correctly Create Threads for C Class Member Functions?

Barbara Streisand
Barbara StreisandOriginal
2024-12-22 04:48:09868browse

How to Correctly Create Threads for C   Class Member Functions?

Creating Threads on Class Member Functions

When working with C classes, a common challenge is creating threads on member functions. Consider the following class:

class c { 
    // ...
    void *print(void *){ cout << "Hello"; }
}

Let's say we have a vector of c objects and want to create a thread on the c.print() function. However, the following code leads to an error:

pthread_create(&t1, NULL, &c[0].print, NULL);

The error message indicates that the function pointer does not match the expected type for the third argument of pthread_create().

Solution:

The error occurs because C class member functions have a hidden this parameter passed implicitly. pthread_create() doesn't know which instance of c to use for the this parameter. To resolve this, we need to use a static class method (which doesn't have a this parameter) or a plain function to bootstrap the class.

Static Class Method Approach:

class C
{
public:
    static void *hello_helper(void *context)
    {
        return ((C *)context)->hello();
    }
};

// ...

C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);

This approach defines a static class method hello_helper(), which has no this parameter and wraps the call to the hello() member function.

Plain Function Approach:

void hello(void *context)
{
    C *c = (C *)context;
    c->hello();
}

// ...

C c;
pthread_t t;
pthread_create(&t, NULL, &hello, &c);

Here, we define a plain function hello() that takes a void pointer passing to it and casts it to an instance of c. We then call the hello() member function on the c instance.

The above is the detailed content of How to Correctly Create Threads for C Class Member Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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