c++ - C++11 Threads - start infinite worker thread from inside a class -


i wanna provide class, holds buffer while reading in data (udp packets or file). fine if start thread main, in case want avoid, user has set new thread himself.

so here code simple make it:

class datacollector {     void startcollect()     {         std::thread t1(readsource);     }      bool readsource()     {         while(1)         {             // read data storage         }     }    }  int main() {     datacollector mydatacollector;     mydatacollector.startcollect();      while(1)     {         // other work, example interpret data     }      return 0; } 

now need help. how can call thread inside startcollect?

edit1: here example of how works now!

// ringbuffertest.cpp : definiert den einstiegspunkt für die konsolenanwendung. //  #include "stdafx.h" #include <thread> #include <windows.h>  class datacollector { private:     //std::thread collecterthread;  public:     datacollector(){}      void startcollect()     {                readsource();     }      bool readsource()     {         while (1)         {             printf("hello readsource!\n");             sleep(1000);         }         return false;     } };   int _tmain(int argc, _tchar* argv[]) {     datacollector mydatacollector;      std::thread t1(&datacollector::startcollect, std::ref(mydatacollector));      t1.join();     return 0; } 

but said hide thread call inside startcollect function.

before destroying active thread object, must either joined (waiting thread finish, cleaning resources) or detached (left run , clean when finished).

so either make thread member variable, can joined later:

void startcollect() {     this->thread = std::thread(&datacollector::readsource, this); }  void waitforcollecttofinish() {     this->thread.join(); } 

or detach it, if don't need ability wait finish, , have other way of signalling data available:

void startcollect() {     std::thread([this]{readsource();}).detach(); } 

you might @ higher-level concurrency facilities, such std::async , std::future. these might more convenient dealing threads directly.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -