Reputation: 14792
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!
Upvotes: 5
Views: 16511
Reputation: 19302
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();
}
Upvotes: 9
Reputation: 90701
You're passing a member function pointer (i.e. &Game::draw
) where a pure function pointer is required. You need to make the function a class static function.
Edited to add: if you need to invoke member functions (which is likely) you need to make a class static function which interprets its parameter as a Game*
and then invoke member functions on that. Then, pass this
as the last parameter of pthread_create()
.
Upvotes: 1
Reputation: 4338
compilation of threads using pthread is done by providing options -pthread
.
Such as compiling abc.cpp would require you to compile like g++ -pthread abc.cpp
else would
give you an error like undefined reference to
pthread_create collect2: ld returned 1 exit status` . There must be some similar way to provide pthread option.
Upvotes: 1