像线程一样调用类方法

时间:2013-09-03 23:17:14

标签: c++ multithreading sdl

我正在使用SDL,但如果可能的话,我接受其他库的任何解决方案(pthread,boost_thread ...)。 我有一节课:

class c_image
{
    public:
        bool _flag_thread;
        int  _id;
        void load (void);
    private:
        int thread_func (void*);
}

c_image::load (void)
{
    SDL_Thread* thread_1;
    if (flag_thread)
        thread_1 = SDL_CreateThread (c_image::thread_func, NULL);
    else
        thread_func (NULL);
}

c_image::thread_func (void* data)
{
    _id = 1;
    ....
    return 0;
}

问题是,如果flag_thread为false,它会像普通函数一样执行thread_func并且工作正常,但如果flag_thread为真,我需要在另一个线程中调用我不知道如何制作它。 SDL_CreateThread行返回错误。我需要方法的线程,因为在thread_func内我需要修改像_id这样的类的成员,如果我在类之外创建线程,我就无法访问到_id

感谢。

编辑: 这就是我现在拥有它的方式,而不是找到一种方法使它工作:

class c_image
{
    public:
        bool _flag_thread;
        int  _id;
        void load (void);
    private:
        static int thread_func_wrapper (void* data);
        int thread_func (void);
}

void c_image::load (void)
{
    SDL_Thread* thread_1;
    if (flag_thread)
        thread_1 = SDL_CreateThread (thread_func_wrapper, NULL, this);
    else
        thread_func();
}

int c_image::thread_func_wrapper (void* data)
{
    c_image* self = static_cast<c_image*>(data);
    return self->thread_func();
}

int c_image::thread_func (void)
{
    printf ("id: %d", _id);
    ....
    return 0;
}

现在它似乎工作正常。我会继续做测试。非常感谢你!

1 个答案:

答案 0 :(得分:2)

问题是SDL_CreateThread是一个“C”样式的接口,所以它不能采用std::function或类似的类型函数对象。相反,您需要创建一个静态函数,该函数将指向引用的指针作为void *data指针:

class c_image
{
  ... 
  static void thread_func_wrapper(void *data);

  int thread_func(void);
};


int c_image::thread_func_wrapper(void *data)
{
   c_image* self = static_cast<c_image*>(data);
   return self->thread_func();
}