没有匹配的函数调用'pthread_create'
No matching function call to 'pthread_create'
我正在使用Xcode和C++来制作一个简单的游戏。问题是以下代码:
#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
// ...
}
但是Xcode给了我错误:"No matching function call to 'pthread_create'
"。我不知道'原因我已经包括pthread.h
了。
怎么了?
谢谢!
正如 Ken 所说,作为线程回调传递的函数必须是 (void*)(*)(void*) 类型的函数。
您仍然可以将此函数作为类函数包含在内,但必须将其声明为静态函数。对于每种线程类型(例如绘制),您可能需要一个不同的线程。
例如:
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();
}
使用 pthread 编译线程是通过提供选项-pthread
来完成的。例如编译 abc.cpp需要您像g++ -pthread abc.cpp
一样进行编译给你一个错误,比如undefined reference to
pthread_create collect2:ld 返回了 1 个退出状态'。必须有一些类似的方法来提供 pthread 选项。
你正在传递一个成员函数指针(即 &Game::draw
),其中需要纯函数指针。您需要使该函数成为类静态函数。
编辑以添加:如果您需要调用成员函数(很可能),则需要创建一个类静态函数,该函数将其参数解释为Game*
,然后在其上调用成员函数。 然后,传递 this
作为 pthread_create()
的最后一个参数。
相关文章:
- Using C++ CryptAPI:CNG Create CSR
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 在 c++11 中为 pthread 设置调度参数
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- pthread只有在线程数量较少时才可以正常工作
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- pthread执行时间比顺序执行时间差
- 使用 -pthread 如何不违反 ODR 规则?
- 使用 pthread 的多线程
- QThread::create 似乎没有将参数传递给函数
- 销毁 pthread 互斥体和 C++ 中的取消初始化顺序
- 函数 AfxEndThread 中的读取访问冲突"pThread-> was nullptr"
- 锁定步进pthread互斥
- Pthread段错误,使用指向main中变量的指针
- pthread导致的内存泄漏
- GCC:--静态链接到pthread的整个存档配方在最近的GCC版本中停止工作
- 正确地编写一个类,并将pthread与vlc库和c++一起使用
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- QThread::create running on UI Thread
- 使用pthread Create创建两个类,并在cpp中相互访问