mardi 24 septembre 2019

How to manage variable state in singleton class?

I am trying to make an application logger program in C++ for Linux/UNIX environment which handles the multi-thread environment efficently. The problem I am currently facing is related to singleton class, allow me show you the code first and then I will ask for the Q which I have digging from last few days-

class Logger {

private:
  int mNumber;


public:
  static Logger& getInstance(int num){

     static Logger object;

     /* 
       I have already solved the problem for single threaded application, below is what I was doing
     */   
     object.setNumber(num);

     /*
       But I can not do the above in multi thread application, even with lock( I prefer pthread) mutexes and semaphores.
     */
     return object;
  }

  void debug(const char* str){
     std::cout << "Num : "  << mNumber << " :: Message : " << str << std::endl;
  }

private:

  void setNumber(const int num){
    this->mNumber = value;
  }  
};  

#define logMe   Logger::getInstance(__LINE__)

void* threadOne(void* args){

   while(true){
      logMe.debug("I am from threadOne");
   }
   return (void*) nullptr;
}// end

int main(int argc, char** argv){

    logMe.debug("Works with single threaded application.");
   /*
     1) Correct me if I am wrong, the above gets expand to
        Logger::getInstance(__LINE__).debug("value");
     2) Now that is the problem, somehow, I want this value to pass to debug method. 
   */

   // This is what I have been trying to do-
   pthread_t tid;
   pthread_create(&tid, nullptr, threadOne, nullptr);

   while (true){
      logMe.debug("I am from Main");
      usleep(2000);     // This is not neccesarry just to check while debugging.
   }
   exit (EXIT_SUCCESS);
}// end

The issue:

Somehow, I want to keep the record of line number and message at the same time. I am not sure if there are other patterns which can save my life. Any help in any direction would really be helpful. THANK YOU in advance.

Aucun commentaire:

Enregistrer un commentaire