Here is my code:
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
pthread_t ntid;void
printids(const char *s) {
printf("%s \n", s);
}
void *
thr_fn(void *arg) {
printids("new thread: ");
return((void *)0);
}
int
main(void) {
pthread_create(&ntid, NULL, thr_fn, NULL);
printids("main thread:");
}
I'm running it on Red Hat Enterprise Linux Workstation release 6.5 .
Here is my compiling command
gcc -ansi -g -std=c99 -Wall -DLINUX -D_GNU_SOURCE threadid.c -o threadid -pthread -lrt -lbsd
Here is the output:
main thread:
new thread:
new thread:
Why "new thread" has been printed twice?
I doubt this may related to buffering mechanism in Linux. But after I added fflush(stdout)
and fsync(1)
in the end of each function. The output is almost the same.
If you run the program several times. The output differs:
main thread:
new thread:
or
main thread:
new thread:
new thread:
Or
main thread:
ntid
and apthread_join()
gives exactly the expected output, btw. – Lovmillapthread_t ntid
definition). – Bunchenew thread:
at all as you don't do apthread_join()
, so the program could end before the new thread had a chance to run. But it's impossible this is printed twice. – Lovmillanew thread:
. – Bunchestdout
from the operating system, but the libc implementation could have a per thread output buffer. – Tubercularprintf
. And no matter if it's implemented using one buffer per process, or one per thread, this duplication should not happen. Especially if it's one buffer per thread. – Apoenzymeldd threadid
? If you're linking in some library with a non-thread-safestdout
stream, that could explain your inconsistent results. – Tactic