一般来说,我假设流不同步,由用户做适当的锁定.但是,做cout标准库中的特殊处理吗?
也就是说,如果多个线程正在写入,cout它们会破坏cout对象吗?据我所知,即使同步,你仍然会得到随机交错的输出,但保证交错.也就是说,cout从多个线程使用是否安全?
该供应商是否依赖?gcc做什么?
重要提示:如果您说"是",请为您的答案提供某种参考,因为我需要某种证明.
我关注的还不是基础系统调用,这些都很好,但是流在顶部添加了一层缓冲.
printf在Linux上使用线程安全写入stdout ?使用低级write命令怎么样?
#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
#include <cstdio>
int main( )
{
char pbuffer[BUFSIZ];
setbuf(stdout, pbuffer);
cout << "hello cout" ;
sleep(5);
cerr << "hello cerr";
sleep(5);
cout << "\nAll done " << endl;
sleep(5);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在我编译并运行上面的程序之后,它的输出是:
hello couthello cerr
All done
Run Code Online (Sandbox Code Playgroud)
但我认为它应该是:
hello cerrhello cout
All done
Run Code Online (Sandbox Code Playgroud)
我想知道,为什么要cerr冲洗缓冲区cout?