为什么使用`printf()`不会引起溢出?
我正在对printf()
进行一些实验,我的代码如下:
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
while(1) printf("a");
}
void bar()
{
while(1) printf("b");
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar); // spawn new thread that calls bar(0)
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
return 0;
}
大量AB会输出。但是我在这里有一个问题:据我所知,printf有一个缓冲区,那么为什么buffer [pos ++]
不会导致溢出?我想使用了一个圆缓冲区,但我不确定。
因此,当缓冲区不完整时,两个线程会同时写入缓冲区,我也编写另一个版本
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
while(1) printf("aaaaaa");
}
void bar()
{
while(1) printf("bbbbbb");
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar); // spawn new thread that calls bar(0)
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
return 0;
}
,但是输出不会像ababab
一样,我想知道Printf如何同时处理写作?
I'm doing some experiments on printf()
, my code is shown below:
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
while(1) printf("a");
}
void bar()
{
while(1) printf("b");
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar); // spawn new thread that calls bar(0)
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
return 0;
}
A lot of ab will output. But I have a question here: as far as I know, printf has a buffer, so why buffer[pos++]
will cause no overflow? I guess a circle buffer is used, but I'm not sure.
So when the buffer is not full, two threads will write to the buffer concurrently, I also write another version
#include <iostream> // std::cout
#include <thread> // std::thread
void foo()
{
while(1) printf("aaaaaa");
}
void bar()
{
while(1) printf("bbbbbb");
}
int main()
{
std::thread first (foo); // spawn new thread that calls foo()
std::thread second (bar); // spawn new thread that calls bar(0)
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
return 0;
}
But the output will not something like ababab
, I wonder how printf deal with writing concurrently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
printf
的实现要注意,如果使用缓冲区,它从未在缓冲区之外写下。实现可能会选择这样做。
C标准说:
The implementation of
printf
takes care that it never writes outside of its buffer in case that it uses a buffer.The implementation may choose to do so.
The C standard says: