c++ When calling the pthread_create function, the members of the incoming class report an error. Solution.

1. Problems arise

I want to convert my C program to C++, because I think the object-oriented method of C++ is very easy to use.

Then I started porting, when I wanted to create a class by calling pthread_create in a class function.

The parameters I give are

s=pthread_create(&id,NULL,run,NULL);


// function prototype

void * THREAD_433::run(void *arg)
{
    void * ret;
    using namespace  std;
    cout<<"hello!\r\n";
    return ret;
}

At this time, it will compile error,

D:\Cprogress\pthread\my_thread.cpp:15: error: cannot convert 'THREAD_433::run' from type 'void* (THREAD_433::)(void*)' to type 'void* (*)(void*)'
     s=pthread_create(&id,NULL,run,NULL);
                                       ^

He says the type doesn't match.

2. Problem solving

A type mismatch occurs. Because the parameter type required by pthread_create is void* (*)(void*), and when run is a member function of a class, its type is a pointer to a member function of void* (Thread_433::)(void*).

We know that the member function of a class will become a global function with a this pointer parameter after being processed by the compiler, so the types are destined to not match.

But if run is declared as static type, the compiler will convert the static form of the function into a global function without this pointer, so its type can match the parameter type required by pthread_create. However, the static member functions of the class cannot access the non-static members of the class, but this can be solved by passing the this pointer.

Modified code: nothing else needs to be changed

void THREAD_433::Init(void)
{

    int s;
    s=pthread_create(&id,NULL,THREAD_433::run,NULL);
    if(s!=0)
            std::cout<<"err!\r\n";
}


/* *********Class Declaration********** */ 
class THREAD_433
{
public:
    THREAD_433 ();
    void Init(void);
    void Delete(void);

private:
    pthread_t id;
    static void *run(void *arg);
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324890492&siteId=291194637