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