0

Take a look at the following sample,

#include <iostream>
#include <thread>

class GPS 
{
public:
    GPS()  { this->init();  }
    ~GPS() {m_thread.join();}
private:
    std::thread m_thread;
    void init()   { m_thread = std::thread(&GPS::update,this); } 
    void update() { /*get data from gps sensor.*/ }; 
};

GPS myGPS;

int main()
{
    return 0;
}

What is/are the consequences of creating an object globally that has its own thread? Is this safe approach? if No, what are the alternatives with the assumption that the object must be global and has an independent thread? Thank you.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
CroCo
  • 5,531
  • 9
  • 56
  • 88
  • Possible duplicate of [Is the main thread allowed to spawn a POSIX thread before it enters main()?](https://stackoverflow.com/questions/21771066/is-the-main-thread-allowed-to-spawn-a-posix-thread-before-it-enters-main) - The question is formulated a bit differently, but the accepted answer is really excellent and does relate very strongly to your question. An alternative would be a Meyers' singleton first initialized at the begin of `main`. – Zulan Jul 18 '17 at 17:55
  • @Zulan This isn't POSIX threads, it is std thread. – Yakk - Adam Nevraumont Jul 18 '17 at 19:32
  • Read the answer. – Zulan Jul 18 '17 at 19:34

1 Answers1

-1

if No, what are the alternatives.

Lazy evalutation: Don't create the thread until the first time it actually is needed.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57