Reputation: 341
I encoutered a weird behavior of pthread_create
function. The code follows:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void *foo( void* a) {
printf("Doing something");
pthread_exit(NULL);
}
int main() {
printf("Main created");
pthread_t thread;
pthread_create( &thread, NULL, foo, NULL );
while(1); // This causes trouble
pthread_join( thread, NULL );
return 0;
}
For some reason, with the while
in place, message from thread is showed after a really long delay. I would expect that after pthread_create call new thread is completely independent from main and thus should not be afected by its code.
Upvotes: 0
Views: 306
Reputation:
This has nothing to do with threads.
You'll find that the same behavior occurs with:
printf("Doing something");
while(1) ;
This is because you didn't include a newline on the end of the string you printed, which causes the line to be buffered. Since no further output is generated, the line may be buffered for a very long time (possibly even forever).
To avoid this, you can either:
Add newlines to all of your output lines, e.g. printf("Doing something\n");
Call fflush(stdout)
after printf()
to force the line to be flushed
Call setvbuf(stdout, NULL, _IONBF, 0)
beforehand to disable all output buffering
Upvotes: 3