Here is my threaded program, which is very simple:
#include <iostream>
#include <thread>
using namespace std;
void myprint(int a)
{
cout << a << endl;
}
int main()
{
thread obj(myprint, 3);
obj.detach();
cout << "end!!!" << endl;
}
What I can’t understand is that the program occasionally has sub-threads that print 3 multiple times, such as:
3
3
end!!!
I have browsed through many sources but have not found a good answer to this question.
I know that std::out is thread-unsafe and understand the garbled output due to race. The issue of duplicate output, however, doesn’t seem to have much to do with race, as it doesn’t occur in join() contexts.
The relevant configuration of the programming environment is as follows
Linux version 5.15.0-48-generic (buildd@lcy02-amd64-080)
(gcc (Ubuntu 11.2.0-19ubuntu1) 11.2.0,
GNU ld (GNU Binutils for Ubuntu) 2.38)
GCC version:
gcc version 11.2.0
2
Answers
Aha,this morning I had a stroke of genius and solve the problem successfully. You just need to test the cpu time that
join()
anddetach()
executed, you will get the answers.I think @Someprogrammerdude is right, it's just that the
join
takes longer to execute, so the problem of duplicate output only occurs indetach()
It’s a buffering issue. Because the process itself only have one
std::cout
object and to that one connected buffer, it will be shared between all the threads.When probably happens is that the thread prints the output, but doesn’t manage to clear the buffer before the thread is preempted and the main thread runs to print its
"end!!!"
message. Since the buffer isn’t clear it will also contain the3
output from the thread, so it’s written again. This is a race condition, and those are bad.The simplest solution is to not detach the thread, and join it before you print the
"end!!!"
message and exit the process.A more complex solution is to add some kind of synchronization between the threads in your processes, so all access to
std::cout
is protected and can run only mutually exclusive from all other access to it.