C++ 中的异步线程安全日志记录(无互斥锁) [英] Asynchronous thread-safe logging in C++ (no mutex)

查看:62
本文介绍了C++ 中的异步线程安全日志记录(无互斥锁)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上正在寻找一种在我的 C++ 中进行异步和线程安全日志记录的方法.

I'm actually looking for a way to do an asynchronous and thread-safe logging in my C++.

我已经探索了线程安全日志记录解决方案,如 log4cpp、log4cxx、Boost:log 或 rlog,但似乎它们都使用互斥锁.据我所知,互斥锁是一种同步解决方案,这意味着所有线程在尝试写入消息时都被锁定,而其他线程则在执行.

I have already explored thread-safe logging solutions like log4cpp, log4cxx, Boost:log or rlog, but it seems that all of them use a mutex. And as far as I know, mutex is a synchronous solution, which means that all threads are locked as they try to write their messages while other does.

你知道解决方案吗?

推荐答案

我认为您的说法是错误的:使用互斥锁不一定等同于同步解决方案.是的,Mutex 用于同步控制,但它可以用于许多不同的事情.例如,我们可以在生产者消费者队列中使用互斥锁,同时日志记录仍在异步发生.

I think your statement is wrong: using mutex is not necessary equivalent to a synchronous solution. Yes, Mutex is for synchronization control but it can be used for many different thing. We can use mutex in, for example, a producer consumer queue while the logging is still happening asynchronously.

老实说,我还没有研究过这些日志库的实现,但是制作一个异步 appender(对于像 lib 这样的 log4j)应该是可行的,它记录器写入生产者消费者队列,另一个工作线程负责写入文件(甚至委托给另一个 appender),以防它没有提供.

Honestly I haven't looked into the implementation of these logging library but it should be feasible to make a asynchronous appender (for log4j like lib) which logger writes to an producer consumer queue and another worker thread is responsible to write to a file (or even delegate to another appender), in case it is not provided.

刚刚在 log4cxx 中进行了一次简短的扫描,它确实提供了一个 AsyncAppender,它执行了我的建议:缓冲传入的日志事件,并异步委托给附加的 appender.

Just have had a brief scan in log4cxx, it does provide an AsyncAppender which does what I suggested: buffers the incoming logging event, and delegate to attached appender asynchronously.

这篇关于C++ 中的异步线程安全日志记录(无互斥锁)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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