C++使用 ostream 进行日志记录

发布于 2025-01-06 11:06:34 字数 358 浏览 0 评论 0原文

我正在制作一个记录器。我想创建一个将流作为输入的函数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

∞觅青森が 2025-01-13 11:06:34

log() 返回一个临时对象,该对象在内存中缓冲所有输出。该对象的析构函数将在表达式末尾运行,并且应该在单个原子操作中将累积的数据刷新到实际流(由您决定使该操作原子化)。

这将使你的第二种语法可行:

log()<<"hello"<<"world"<<10<<"\n";

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:

log()<<"hello"<<"world"<<10<<"\n";
才能让你更想念 2025-01-13 11:06:34

您无法创建您想要的函数。但是,您可以创建一个宏来为您处理这些内容:

// "log" may be defined in the <cmath> header file
// so undefine it if needed
#ifdef log
# undef log
#endif
#define log(stream)          \
    do {                     \
        acquire_lock();      \
        std::cout << stream; \
        release_lock();      \
    } while(0)

您必须将 acquire_lockrelease_lock 调用更改为适合您的调用。当然,也使用适合您的流。

You can't create a function like the one you want. You can, however, create a macro that handles that stuff for you:

// "log" may be defined in the <cmath> header file
// so undefine it if needed
#ifdef log
# undef log
#endif
#define log(stream)          \
    do {                     \
        acquire_lock();      \
        std::cout << stream; \
        release_lock();      \
    } while(0)

You have to change the acquire_lock and release_lock calls to the proper ones for you. And of course use a stream that is appropriate for you as well.

丢了幸福的猪 2025-01-13 11:06:34

在C++03中,所有操作都不是线程安全的

in C++03 all operations are not thread safe

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文