如何在单例类中管理变量状态?

时间:2019-09-24 11:57:30

标签: c++ multithreading c++11 c++14

我试图在C ++中为Linux / UNIX环境制作一个应用程序记录程序,该程序可以有效地处理多线程环境。我当前面临的问题与单例类有关,请让我先向您展示代码,然后再询问最近几天挖掘的问题-

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

问题:

我想同时保留行号和消息的记录。   我不确定是否还有其他方法可以挽救我的生命。任何方向的帮助都将真正有帮助。提前谢谢您。

1 个答案:

答案 0 :(得分:0)

将执行工作的类与保存值的类分开:

struct Logger {
  struct Line {
    Logger &log;
    int n;
    void debug(const char *s)
    {log.debug(n,s);}
  };

  Line at(int n) {return {*this,n};}

private:
  void debug(int n,const char *s)
  {std::cout << "Num : "  << n << " :: Message : " << s << std::endl;}
};

您可以使Logger成为Line的朋友,以避免暴露出可构造的帮助者,但是任何人都可以将任何东西传递给at

请注意,Logger::debug不使用this;如果在真实情况下是正确的,则使其成为static(或根本不成为成员函数),然后可以简化Line并避免单例,这是一个主要的胜利(尤其是在多线程环境中)