0

I'm using a pthread, that at the moment, is sleeping for 1 second then writing to a log file and printing to the screen. In my int main(), there's a while loop that runs forever right now, but will eventually stop. In the loop, it's accessing the logger, which is my singleton class, writing to it, and printing to the screen as well. Here's the logger get instance funciton...

Logger* Logger::getInstance(){
if(logger == NULL){
    logger = new Logger();
}

return logger;

}

Here's the thread function that waits for a second...

void Beacon::send(){
while(1){
    sleep(1);
    Logger* logger = Logger::getInstance();
        logger->log("Sending");
}
}

Here's the while loop that also prints to the logger. The checkQueue funciton doesn't do anything right now...

while(!a){

        logger->getInstance()->log("Checking...");
        checkQueue();



        if(a == true)
            break;

}

When I have it logging in the while loop, It will only print checking to the screen. When I comment that out, it will print sending to the screen. Do I need to have a double lock check in the get instance function? I've been trying to look into that, but don't understand how to implement it.

ThatBoiJo
  • 319
  • 2
  • 14
  • 2
    I can't see any threading or locking code there. Also I would recommend the so-called "Mayer" singleton pattern: https://stackoverflow.com/questions/1008019/c-singleton-design-pattern – Galik Jul 08 '16 at 15:58
  • is this c++11 or c++03? – Richard Hodges Jul 08 '16 at 16:02
  • Does `Beacon's` "sending" start showing up if you put a short sleep inside the main loop? You have not shown your locking code, but it's possible that the loop in main is too tight and holding the lock too often making it very improbable for `Beacon` to grab the lock. – Always Confused Jul 09 '16 at 16:18
  • Yeah that actually does happen. I've been trying to use locks, but don't understand them that well. – ThatBoiJo Jul 11 '16 at 12:00

1 Answers1

2

The easiest way to make a singleton in C++11 is this:

MyClass& MyClass::getInstance() {
    static MyClass instance;
    return instance;
}

The initialization of local static variables are thread safe in C++11

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • I also did this at one point, and it would still continuously print out checking and never printed sending. – ThatBoiJo Jul 08 '16 at 19:02
  • That would be a race inside the `Logger` class. You can try using mutex or condition variables to prevent it. Ensure that you flush the internal buffer of your logger too. – Guillaume Racicot Jul 08 '16 at 19:20