c++ - 没有对 'pthread_create' 的匹配函数调用

标签 c++ xcode class pthreads

我正在使用 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 给我错误:“没有匹配的函数调用‘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();
}

关于c++ - 没有对 'pthread_create' 的匹配函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10389384/

相关文章:

ios - 更新到 MacOS Catalina 后 Xcode 无法打开

c++ - glGetUniformfv 用于声明为数组的统一变量

c++ - POCO Net C++ 库中的代理身份验证

iOS 应用程序可以在模拟器上运行,但不能在真实设备上运行

ios - 如何在自定义 UIButton 中实现 .isHighlighted 动画?

c# - 将类的对象声明为 null

c# - 尝试让 main/form1 以外的类相互交互是不是一种不好的形式?

c++ - const char* 和字符串比较在 C++ 中如何工作?

c++ - DJI OSDK 通过串口向 DJI Matrice 100 发送命令时的命令延迟

c++ - 在创建对象 C++ 之前设置静态变量