[英]No matching function call to 'pthread_create'
I'm using Xcode and C++ to make a simple game. 我正在使用Xcode和C ++制作一个简单的游戏。 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'
". 但是Xcode给了我错误:“
No matching function call to 'pthread_create'
”。 I haven't an idea 'cause of I've included pthread.h
already. 我不知道'因为我已经包含了
pthread.h
。
What's wrong? 怎么了?
Thanks! 谢谢!
As Ken states, the function passed as the thread callback must be a (void*)(*)(void*) type function. 正如Ken所说,作为线程回调传递的函数必须是(void *)(*)(void *)类型函数。
You can still include this function as a class function, but it must be declared static. 您仍然可以将此函数作为类函数包含在内,但必须将其声明为static。 You'll need a different one for each thread type (eg 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();
}
compilation of threads using pthread is done by providing options -pthread
. 使用pthread编译线程是通过提供选项
-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` . 比如编译abc.cpp会要求你编译像
g++ -pthread abc.cpp
else会给你一个错误,比如undefined reference to
pthread_create collect2:ld返回1退出状态`。 There must be some similar way to provide pthread option. 必须有一些类似的方法来提供pthread选项。
You're passing a member function pointer (ie &Game::draw
) where a pure function pointer is required. 你正在传递一个成员函数指针(即
&Game::draw
),其中需要一个纯函数指针。 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. 编辑添加:如果你需要调用成员函数(很可能),你需要创建一个类静态函数,将其参数解释为
Game*
,然后在其上调用成员函数。 Then, pass this
as the last parameter of pthread_create()
. 然后,将
this
作为pthread_create()
的最后一个参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.