0
votes

I want the Run function to run its own thread, but it shows an error, how to make it compatible with each other

Error : argument of type "void (cMain::)(void *arg)" is incompatible with parameter of type "void *(__cdecl *)(void *)"

cMain.h

#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>

using std::string;
class cMain
{ 
public:
    cMain();
    ~cMain();

public:
    wxListView *Listview1 = nullptr;
    
    void *Run(void *arg);
    int main();
};

cMain.cpp

void * cMain::Run(void *arg)
{
    int i = 0;
    while (true)
    {
        i += 1;
        Listview1->SetItem(0, 0, std::to_string(i));

        Sleep(200);
    }

    pthread_exit(NULL);

    return 0;
}

int cMain::main()
{
    pthread_t my_thread;

    int ret;

    ret = pthread_create(&my_thread, NULL, &Run, NULL);
    if (ret != 0) {
        MessageBox(NULL, L"Error: pthread_create() failed", L"AA", MB_OK);
        exit(EXIT_FAILURE);
    }
}

error code : ret = pthread_create(&my_thread, NULL, &Run, NULL);

1
You tagged your question with c. In the title you have c++. You use C-specific linux thread interface - pthread_*. Your code is in C++. In C++ use C++ - use std::thread. So you write in C or in C++? argument of type "void (cMain::)(void *arg)" is incompatible with parameter of type "void *(__cdecl *)(void *)" and research what is a function member and what is a pointer to member function and how to use it. You can't pass a pointer to class member function to pthread. You have to pass void(void*) function. - KamilCuk
You can pass an object pointer as the last argument to pthread_create(). Your thread function, (free or static), could then retrieve its parameter, cast to object class and then call the method on it. - Martin James

1 Answers

0
votes

The typical solution is to do this:

class cMain
{ 
public:
    cMain();
    ~cMain();

public:
    wxListView *Listview1 = nullptr;
    
    void *Run();
    static void *cRun(void *p) {
      return reinterpret_cast<cMain*>(p)->Run();
    }
...
};

int cMain::main()
{
    pthread_t my_thread;
    int ret;

    ret = pthread_create(&my_thread, NULL, &cRun, this);
    ...

That is: create a static function in your class, whose sole purpose is to convert the void* pointer into the instance of your class, so other functions on that instance can be invoked.