Logging in multi threaded application, Using mutex in a constructor

萝らか妹 提交于 2020-01-04 14:06:31

问题


I have been writing a C++ method entry/exit logger, based on RAII. The usage is something like this:

void Class::Method()
{
    METHOD_NAME( "Class::Method" );   // I know: I could use __FUNCTION__ instead ;<)
    …
}

Logger class:

#define METHOD_NAME(name)  TraceLogger  _traceLog(name);

TraceLogger::TraceLogger( const std::string& theContext )
{
    <lock mutex here>
    // Trace logging code here
}

TraceLogger::~TraceLogger()
{
    <lock mutex here>
    // Trace logging code here
}

The problem is that the code is not thread safe. If I add a mutex here to protect the code, will it be correctly used, since it would be constructed and then immediately used in the TraceLogger constructor?

We are a windows VS2008 shop (that is, there is no std::mutex available), and are using home grown thread locking code. I have tried using this, and it doesn't seem to work.

Are there any standard ways to do to this?

Thanks, Paul


回答1:


Use a lock free queue based structure encapsulated with a worker thread class. All the application threads will put the log strings into the object queue. The worker thread would scan the queue and log the data into the file. Make the worker thread such that it blocks on the queue if it is empty.

In C++ concurrency talk Herb Sutter describes it as below:

The logger takes a lambda that can log a string. The worker has a queue of lambda and will execute the lambdas serially.

class log 
{
  fstream f;
  worker_thread w;

  public:
   void println( /*…*/ ) 
   {
      w.send([=]{f << /*…*/ << endl;
   });}

};


来源:https://stackoverflow.com/questions/15923233/logging-in-multi-threaded-application-using-mutex-in-a-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!