C++使用 ostream 进行日志记录
我正在制作一个记录器。我想创建一个将流作为输入的函数 log()
。
例如:
log("hello"<<" "<<"world"<<10<<"\n");
我也希望它是线程安全的。
我已经重新定义了 <<
运算符,因此我可以执行以下操作:
log()<<"hello"<<"world"<<10<<"\n"
但是此操作不是线程安全的。
我怎样才能使它线程安全?
I'm making a logger. I want to create a function log()
that takes a stream as input.
For instance:
log("hello"<<" "<<"world"<<10<<"\n");
I also want it to be thread safe.
I've redefined the <<
operator so I can do:
log()<<"hello"<<"world"<<10<<"\n"
But this operation is not thread safe.
How can I make it thread safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
让
log()
返回一个临时对象,该对象在内存中缓冲所有输出。该对象的析构函数将在表达式末尾运行,并且应该在单个原子操作中将累积的数据刷新到实际流(由您决定使该操作原子化)。这将使你的第二种语法可行:
Have
log()
return a temporary object that buffers all output in memory. The destructor for this object will run at the end of the expression, and should flush the accumulated data to the actual stream in a single atomic operation (up to you to make that operation atomic).That will make your second syntax feasible:
您无法创建您想要的函数。但是,您可以创建一个宏来为您处理这些内容:
您必须将
acquire_lock
和release_lock
调用更改为适合您的调用。当然,也使用适合您的流。You can't create a function like the one you want. You can, however, create a macro that handles that stuff for you:
You have to change the
acquire_lock
andrelease_lock
calls to the proper ones for you. And of course use a stream that is appropriate for you as well.在C++03中,所有操作都不是线程安全的
in C++03 all operations are not thread safe