c++ - Call a class method like a thread -
i'm using sdl, accept solution other libraries if possible (pthread, boost_thread...). have class:
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; }
the problem if flag_thread
false, execute thread_func
normal function , works fine, if flag_thread
true, need call in different thread , have no idea how make it. line of sdl_createthread
return error. need thread of method because inside thread_func
need modify elements _id
member of class, , if make thread outside of class don't have access _id
.
thanks.
edit: how have now, , not find way make work:
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; }
now seems work fine. continue doing tests. much!
the problem sdl_createthread
"c" style interface, can't take std::function
or similar type function object. instead, need create static function takes pointer reference void *data
pointer:
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(); }
Comments
Post a Comment