登录多线程应用程序,在构造函数中使用mutex [英] Logging in multi threaded application, Using mutex in a constructor

查看:283
本文介绍了登录多线程应用程序,在构造函数中使用mutex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在写一个基于RAII的C ++方法入口/出口记录器。用法如下:

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

记录器类:

#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
}

问题是代码不是线程安全的。如果我在这里添加一个互斥体来保护代码,它会被正确使用,因为它会被构造,然后立即在TraceLogger构造函数中使用?

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?

我们是一个windows VS2008商店(也就是说,没有std :: mutex可用),并且使用自制线程锁定代码。我已经尝试使用这个,它似乎不工作。

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.

有什么标准的方法吗?

感谢,
保罗

推荐答案

使用基于工作线程类。所有应用程序线程都会将日志字符串放入对象队列中。工作线程将扫描队列并将数据记录到文件中。

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.

在C ++并发性谈话中,Herb Sutter将其描述如下:

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

日志记录器使用一个可以记录字符串的lambda。工人有一个lambda队列,将会连续执行lambdas。

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

};

这篇关于登录多线程应用程序,在构造函数中使用mutex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆