【问题标题】:How to manage variable state in singleton class?如何管理单例类中的变量状态?
【发布时间】:2019-09-24 11:57:30
【问题描述】:

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

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

问题:

不知何故,我想同时记录行号和消息。 我不确定是否还有其他模式可以挽救我的生命。任何方向的任何帮助都会很有帮助。提前谢谢你。

【问题讨论】:

  • #define logMe(s) Logger::getInstance().debug(__LINE__, s) 和 debug 将行号作为参数怎么样?
  • 我不是在讨论这是否是最好的,甚至是正确的日志方法,但要解决您的问题,只需调用 Log as logMe("I am from Main"); 并将 logMe 定义为:#define logMe(x) Logger::getInstance(__LINE__).debug(std::string((x)) + __LINE__) ,或类似的东西
  • 方法参数仍然是启动时的选项。但是可以说,它为用户提供了显式更改参数值的权力。你知道我的意思。 @Eljay
  • 让我检查一下@Amadeus。谢谢。
  • 我猜不是,我也超载了"logMe << "I am from main" << std::endl; @Amadeus

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


【解决方案1】:

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

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 并避免单例,这是一个重大胜利(尤其是在多线程环境中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-24
    • 1970-01-01
    • 2021-12-10
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    相关资源
    最近更新 更多