C++ Inheritance and Pthreads with Virtual Worker Functions -
i have class i'm trying implement abstract class maximize code reuse. however, major part of commonality between 2 derived classes lies in fact each has consumer , producer thread. i'm wondering if can have each static member function call virtual member function of underlying work.
basically, following code allowed or doing super hacky, or compiler yell/scream @ me?
// in abstractclass.h class abstractclass { // code here including constructors/destructors protected: virtual int worker() = 0; // derived class provides implementation private: static void* thread(void* args); }; // in abstractclass.cpp static void* abstractclass::thread(void* args) { abstractclass myobject = static_cast<abstractclass*>(args); myobject->worker(); }
basically i'm wondering if derived class "worker" ever called way? note p_thread_create() called passing in thread() function.
thanks try improve understanding of inheritance , virtual functions , how can use maximize code reuse.
yes code looks fine , assumptions correct. purpose of virtual functions derived version of function called no matter superclass signature method called on.
using pthreads , c++, approach using reasonable , not hackey. however, create threads in separate class contain static class method. stop threads being mixed in derived classes.
struct threadmanager { threadmanager(abstractworker* worker) { mworker = worker; mthread = threadstart(threadfunc, this); /* made thread code :) */ } ~threadmanager() { threadstop(mthread); } static void* threadfunc(void* args) { threadmanager* manager = static_cast<threadmanager*>(args); manager->mworker->work(); } abstractworker* mworker; thread mthread; }
note when using pthreads static function required.
Comments
Post a Comment