I write a program using pthread.
Environment:windows 7 , CYGWIN_NT-6.1 i686 Cygwin , gcc (GCC) 4.5.3
The source code
#include<stdio.h>
#include<pthread.h>
void *th_func(void *p)
{
int iLoop = 0;
for(iLoop = 0;iLoop<100;iLoop++)
{
printf("Thread Thread Thread Thread\n");
}
return;
}
int main()
{
int iLoop = 0;
pthread_t QueThread;
printf("Main : Start Main\n");
printf("Main : Start Create Thread\n");
pthread_create(&QueThread,NULL,th_func,NULL);
printf("Main : End Create Thread\n");
for(iLoop = 0;iLoop<100;iLoop++)
{
printf("Main Main Main Main\n");
}
pthread_join(QueThread,NULL);
printf("Main : End Main\n");
printf("---------------\n");
return 0;
}
When I compile the source code, there are no warnings or errors,but it’s output is weird.
A part of it’s output
Main : Start Main
Main : Start Create Thread
Thread Thread Thread ThreThread Thread Thread Thread
Main Main Main Main
Thread Thread Thread Thread
Main Main Main Main
I want to know the cause of such phenomenon.
In this output, Main : End Create Thread is not printed completely. And at line 3, a newline \n at the end of "Thread Thread Thread Thread\n" disappear.
Is everyone’s output like this? It does not occur every time, but occurs sometime.
If I use mutex to call printf safely,the weird output seem to be stopped.
POSIX says printf is thread-safe, and according to Cygwin.com, cygwin provides posix-style API. However, there is the unexpected output.
Is printf really thread-safe?
I executed the same program 100 times in Linux(Ubuntu), and this output did not occur.
In addition, I have not understood the reason why some words on the output disappeared.
This looks like it may be a bug in Cygwin, or maybe something is misconfigured. Several answer here indicate that ‘thread safe’ only promises that the function won’t cause harm to the program, and that thread safety doesn’t necessarily mean that a function is ‘atomic’. But, as far as I know, POSIX doesn’t formally define ‘thread safe’ (if anyone has a pointer to such a definition, please post it in a comment).
However, not only does POSIX specify that
printf()is thread safe, POSIX also specifies that:Since
printf()implicitly references thestdoutFILE*object, allprintf()calls should be atomic with respect to each other (and any other function that usesstdout).Note that this might not be true on other systems, but in my experience it does hold true for many multi threaded systems.