1

我正在使用 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为假,它会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;
}

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

4

1 回答 1

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();
}
于 2013-09-03T23:22:53.107 回答