C++ 像线程一样调用类方法
我使用SDL,但如果可能的话,我接受其他库的任何解决方案(pthread、boost_thread…)。 我有一门课:C++ 像线程一样调用类方法,c++,multithreading,sdl,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* thr
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\u thread
为false,它将像正常函数一样执行thread\u func
,并且工作正常,但是如果flag\u thread
为true,我需要在另一个线程中调用,我不知道如何进行调用。SDL_CreateThread
的行返回一个错误。我需要该方法的线程,因为在thread\u func
中,我需要修改类成员的\u id
等元素,如果我使线程位于类之外,我就无法访问\u 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;
}
类c_图像
{
公众:
布尔(bool)标志(bool)线程;;
内部id;
空隙荷载(空隙);
私人:
静态int线程函数包装器(void*数据);
int thread_func(void);
}
void c_图像::加载(void)
{
SDL_螺纹*螺纹_1;
如果(标记线程)
thread_1=SDL_CreateThread(thread_func_包装器,NULL,this);
其他的
thread_func();
}
int c_image::线程函数包装器(void*data)
{
c_image*self=静态_cast(数据);
返回self->thread_func();
}
int c_image::thread_func(void)
{
printf(“id:%d”,\u id);
....
返回0;
}
现在它似乎工作得很好。我会继续做测试。非常感谢 问题在于
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();
}
类c_图像
{
...
静态无效线程函数包装器(无效*数据);
int thread_func(void);
};
int c_image::线程函数包装器(void*data)
{
c_image*self=静态_cast(数据);
返回self->thread_func();
}
编译器是否有错误?如果是,什么错误?编译器返回:错误:从类型“int(c_image::*)(void*)”转换为类型“int*”无效。谢谢您的回答。我正在尝试你写的东西,现在它可以编译了,但是当执行时,线程返回一个分段错误。在调试器中,我看到公共成员_id和其他成员为空,并且_id可以是我之前设置的另一个值。是的,您将需要SDL_CreateThread(c_image::thread_func,NULL,this)代码>也一样-否则它将使用一些“随机的东西”作为self
指针,这可能不起作用。还要注意,我刚刚将返回类型中的void
更改为int
-这是SDL_CreateThread
所期望的。我不明白。我不知道我需要把SDL\u CreateThread
和thread\u func\u wrapper
放在哪里,我很困惑,抱歉。SDL\u CreateThread现在放在哪里了。但是您可以使用SDL\u createThread(thread\u func\u wrapper,NULL,this)调用它。对不起,我把上面的评论搞乱了,忘了将thread\u func
更改为thread\u func\u包装器
。