【发布时间】: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