Takashi Ikejima Takashi Ikejima - 1 month ago 4
C Question

weird output when I use pthread and printf

I write a program using


Environment:windows 7 , CYGWIN_NT-6.1 i686 Cygwin , gcc (GCC) 4.5.3

The source code


void *th_func(void *p)
int iLoop = 0;

for(iLoop = 0;iLoop<100;iLoop++)
printf("Thread Thread Thread Thread\n");


int main()
int iLoop = 0;
pthread_t QueThread;

printf("Main : Start Main\n");

printf("Main : Start Create Thread\n");
printf("Main : End Create Thread\n");

for(iLoop = 0;iLoop<100;iLoop++)
printf("Main Main Main Main\n");


printf("Main : End Main\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
at the end of
"Thread Thread Thread Thread\n"

Is everyone's output like this? It does not occur every time, but occurs sometime.

If I use mutex to call
safely,the weird output seem to be stopped.

POSIX says
is thread-safe, and according to Cygwin.com, cygwin provides posix-style API. However, there is the unexpected output.

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:

All functions that reference ( FILE *) objects shall behave as if they use flockfile() and funlockfile() internally to obtain ownership of these ( FILE *) objects.

Since printf() implicitly references the stdout FILE* object, all printf() calls should be atomic with respect to each other (and any other function that uses stdout).

Note that this might not be true on other systems, but in my experience it does hold true for many multi threaded systems.