For starters, as far as I remember, compiling with "-pthread" is equivalent to compiling with "-D_REENTRANT -lpthread", so the only difference is there. Note that printf, etc. They are not reentrant because they work with a global buffer.
Having said that, I, unfortunately, could not recreate the interesting part of your problem (your printf inside the target function of the stream seems to have been called twice). Each compilation method (-lpthread and -pthread) gives me the same result: I get fingerprints from inside main, but none of the print from the target of the thread (as you mentioned, you saw it when you first started). I think that this is just a synchronization problem, while the purpose of the stream does not “get close” to printing in front of the main outputs. In fact, just sleeping for 1/100 of a second, before returning from the main one, it gets me the seal of the target’s goal. Try and let us know what you see:
#include<stdio.h> #include<stdlib.h> #include<limits.h> #include<string.h> #include<pthread.h> #include <unistd.h> void * func(void * temp) { printf("inside function\n"); return NULL; } int main() { pthread_t pt1; printf("creating thread\n"); pthread_create(&pt1,NULL,&func,NULL); printf("inside main created thread\n"); /* ZzzzzZZZ... */ usleep(10000); return 0; }
I played with a delay time and even with 1/1000000 of a second: USleep (1); I still get all the expected printfs. As sleep latency decreases, printing is likely to occur out of order, which I expect to see.
So, regarding multiple prints: as mentioned above, printf, etc. work with global structures and are not reentrant. I would be interested to see your result if you reset stdout after your printf, all protected by a mutex:
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include <pthread.h> #include <unistd.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * func(void * temp) { pthread_mutex_lock(&mutex); printf("inside function\n"); fflush(stdout); pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t pt1; pthread_mutex_lock(&mutex); printf("creating thread\n"); fflush(stdout); pthread_mutex_unlock(&mutex); pthread_create(&pt1,NULL,&func,NULL); pthread_mutex_lock(&mutex); printf("inside main created thread\n"); fflush(stdout); pthread_mutex_unlock(&mutex); usleep(10000); return 0; }
EDIT
Sorry, I was not 100% clear when I suggested using fflush () above. I believe that the problem is that you interrupt the time during which characters are pushed onto the screen and when the buffer is cleared. When the buffers then really turned red, you effectively pushed your line twice.