c++ - init a thread which is a member variable inside of an constructor -
i trying write resourcecach should have thread loads , unloads objects of different types. started idea of having thread member variable , list wich std::string
s represent path files load / unload. there method called work() should executed thread. enaugh talk.
the question is: how init thread inside of constructor?
.h
class resourcecach { public: resourcecach(); ~resourcecach(); void init(); bool stopthread(); void load(std::string path); void unload(std::string path); private: thread m_worker; // ptr? reference? right? vector<std::string> m_toload; vector<std::string> m_tounload; void work(); };
and cpp should (this not work)
resourcecach::resourcecach() { init(); } resourcecach::~resourcecach() { } void resourcecach::init() { m_worker(resourcecach::work, "resourcecach-thread"); } void resourcecach::work(){ } bool resourcecach::stopthread(){ if (m_worker.joinable()) { m_worker.join(); return true; } else { return false; } }
we talking std::thread
. how can this? , "way" start this?
you can initialise in usual way, in initialiser list:
resourcecach::resourcecach() : m_worker([this]{work();}) {}
although, if that, should declare last make sure other member variables initialised before thread can access them.
if want defer it, leave default-initialised, , move thread later:
m_worker = std::thread([this]{work();});
note: i'm assuming it's std::thread
, although constructor you're trying call looks non-standard. if it's non-standard thread type, answer may not apply.
Comments
Post a Comment