No function call for 'pthread_create'

I use Xcode and C ++ to create 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 an error: " No matching function call to 'pthread_create'". I have no idea because I already turned it on pthread.h.

What's wrong?

Thank!

+3
source share
3 answers

According to Ken, a function passed as a stream callback should be a function of type (void *) (*) (void *).

You can enable this function as a class function, but it must be declared as static. For each type of stream (e.g. draw) you will need a different option.

For instance:

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 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();
}
+6
source

pthread -pthread. , abc.cpp , , g++ -pthread abc.cpp else undefined reference to pthread_create collect2: ld 1 `. pthread.

+1

You pass a pointer to a member function (i.e. &Game::draw) where a clean pointer to the function is required. You need to make the function a static class function.

Edited to add: if you need to call member functions (which is quite likely), you need to create a static class function that interprets its parameter as Game*, and then calls member functions on this. Then pass thisas the last parameter pthread_create().

+1
source

All Articles