'Why concurrent using `printf()` not causing overflow?
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?
Solution 1:[1]
so why buffer[pos++] will cause no overflow?
The implementation of printf takes care that it never writes outside of its buffer in case that it uses a buffer.
I guess a circle buffer is used
The implementation may choose to do so.
I wonder how printf deal with writing concurrently?
The C standard says:
Each stream has an associated lock that is used to prevent data races when multiple threads of execution access a stream, and to restrict the interleaving of stream operations performed by multiple threads. Only one thread may hold this lock at a time. The lock is reentrant: a single thread may hold the lock multiple times at a given time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eerorika |
