iostream线程安全,cout和cerr是否必须分别锁定? [英] iostream thread safety, must cout and cerr be locked separately?

查看:175
本文介绍了iostream线程安全,cout和cerr是否必须分别锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,为避免输出混合,多个线程对cout和cerr的访问必须同步。在同时使用cout和cerr的程序中,单独锁定它们是否足够?还是同时写cout和cerr仍然不安全?

I understand that to avoid output intermixing access to cout and cerr by multiple threads must be synchronized. In a program that uses both cout and cerr, is it sufficient to lock them separately? or is it still unsafe to write to cout and cerr simultaneously?

编辑说明:我了解cout和cerr在C ++ 11中是线程安全的。我的问题是,不同线程对cout的写操作和对cerr的写操作是否同时以两种对cout的写操作可以相互干扰(导致交错输入等)。

Edit clarification: I understand that cout and cerr are "Thread Safe" in C++11. My question is whether or not a write to cout and a write to cerr by different threads simultaneously can interfere with each other (resulting in interleaved input and such) in the way that two writes to cout can.

推荐答案

如果执行此函数:

void f() {
    std::cout << "Hello, " << "world!\n";
}

从多个线程中,您将获得或多或少的随机交织这两个字符串分别是 Hello, world\n 。那是因为有两个函数调用,就像您编写了这样的代码一样:

from multiple threads you'll get a more-or-less random interleaving of the two strings, "Hello, " and "world\n". That's because there are two function calls, just as if you had written the code like this:

void f() {
    std::cout << "Hello, ";
    std::cout << "world!\n";
}

为防止这种交错,您必须添加一个锁:

To prevent that interleaving, you have to add a lock:

std::mutex mtx;
void f() {
    std::lock_guard<std::mutex> lock(mtx);
    std::cout << "Hello, " << "world!\n";
}

也就是说,交织问题无能为力 cout 。这与使用它的代码有关:有两个单独的插入文本的函数调用,因此,除非您防止多个线程同时执行相同的代码,否则在函数调用之间存在线程切换的可能,这使您可以

That is, the problem of interleaving has nothing to do with cout. It's about the code that uses it: there are two separate function calls inserting text, so unless you prevent multiple threads from executing the same code at the same time, there's a potential for a thread switch between the function calls, which is what gives you the interleaving.

请注意,互斥锁不能阻止线程切换。在前面的代码片段中,它防止了从两个线程同时执行内容 f()

Note that a mutex does not prevent thread switches. In the preceding code snippet, it prevents executing the contents of f() simultaneously from two threads; one of the threads has to wait until the other finishes.

如果您还写到 cerr ,则其中一个线程必须等到另一个完成为止。

If you're also writing to cerr, you have the same issue, and you'll get interleaved output unless you ensure that you never have two threads making these inserter function calls at the same time, and that means that both functions must use the same mutex:

std::mutex mtx;
void f() {
    std::lock_guard<std::mutex> lock(mtx);
    std::cout << "Hello, " << "world!\n";
}

void g() {
    std::lock_guard<std::mutex> lock(mtx);
    std::cerr << "Hello, " << "world!\n";
}

这篇关于iostream线程安全,cout和cerr是否必须分别锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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