I recently endeavoured to learn about multiple threading, and ran into the following unexpected – to me, at least – behaviour: printf just will not print more than a line at once when called in the very simple following code:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
char buffer[2];
void * thread_routine(void * args){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
printf("test %s\n test\n", buffer);
pthread_mutex_unlock(&mutex);
return(NULL);
}
int main(void){
pthread_t thread;
pthread_create(&thread, NULL, thread_routine, NULL);
sleep(1);
buffer[0] = 'c';
buffer[1] = '\0';
pthread_mutex_lock(&mutex);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sleep(10);
return(0);
}
The output is
test c
(wait for 10 seconds and)
test prompt$]
What is wrong with this code? How come I can’t get printf to print two lines at once? Please note that blocking stdout with flockfile and unlocking with funlockfile does nothing to improve the situation.
If your program printed
test prompt$]at the end as you say, this means that the version that you executed didn’t have the second newline in"test %s\n test\n".Newlines are important, since this is when the output gets flushed to the screen. See Why does printf not flush after the call unless a newline is in the format string? for an explanation and recommendations.
Try re-compiling and re-running the exact code from your question, and I bet it’ll work as expected (it certainly does on my box).