Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No matching function call to 'pthread_create'

I'm using Xcode and C++ to make a simple game. The problem is the following code:

#include <pthread.h>

void *draw(void *pt) {
    // ...
}

void *input(void *pt) {
    // ....
}

void Game::create_threads(void) {
    pthread_t draw_t, input_t;
    pthread_create(&draw_t, NULL, &Game::draw, NULL);   // Error
    pthread_create(&input_t, NULL, &Game::draw, NULL);  // Error
    // ...
}

But Xcode gives me the error: "No matching function call to 'pthread_create'". I haven't an idea 'cause of I've included pthread.h already.

What's wrong?

Thanks!

like image 933
qwertz Avatar asked Dec 28 '22 01:12

qwertz


1 Answers

As Ken states, the function passed as the thread callback must be a (void*)(*)(void*) type function.

You can still include this function as a class function, but it must be declared static. You'll need a different one for each thread type (e.g. draw), potentially.

For example:

class Game {
   protected:
   void draw(void);
   static void* game_draw_thread_callback(void*);
};

// and in your .cpp file...

void Game::create_threads(void) {
   //  pass the Game instance as the thread callback's user data
   pthread_create(&draw_t, NULL, Game::game_draw_thread_callback, this);
}

static void* Game::game_draw_thread_callback(void *game_ptr) {
   //  I'm a C programmer, sorry for the C cast.
   Game * game = (Game*)game_ptr;

   //  run the method that does the actual drawing,
   //  but now, you're in a thread!
   game->draw();
}
like image 71
Tom Avatar answered Jan 12 '23 14:01

Tom