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.