Logging in multi threaded application, Using mutex

2019-07-17 14:29发布

问题:

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;
   });}

};