For starters, as far as I can remember, compiling with "-pthread" is equivalent to compiling with "-D_REENTRANT -lpthread", so that's the only difference there.
Note that printf and the like are not reentrant because they operate on a global buffer.
Having said that, I was unfortunately not able to recreate the interesting part of your problem (your printf inside the thread target function seeming to have been called twice). Each method of compilation (-lpthread and -pthread) gives me the same result: I get the prints from inside main, but none of the printing from within the thread target (as you mentioned you saw on your first run). I think this is just a timing issue, with the thread target not "getting around to" printing before main exits. In fact, just sleeping for 1/100 second before returning from main gets me the thread target function's printing. Give it a 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 around with the delay time, and even with 1/1000000 second:
usleep(1);
I still get all of my expected printfs. As the sleep delay decreases, the printing is more likely to occur out of order, which I would expect to see.
So regarding the multiple prints: As many before me pointed out, printf and the like operate on global structures, and are not reentrant. I'd be interested to see your output if you flushed stdout after your printf, all being 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
I'm sorry, I wasn't 100% clear when I suggested using fflush() above. I believe that the problem is that you are being interrupted between the time that the characters are pushed to the screen and when the buffer is flushed. When the buffer is then actually truely flushed, you've effectively pushed your string twice.