没有匹配的函数调用'pthread_create'

No matching function call to 'pthread_create'

本文关键字:create pthread 函数调用      更新时间:2023-10-16

我正在使用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() 的最后一个参数。