0

sleep() function gives me problem in a program. I have declared only one mutex, one condition variable and one global variable:

pthread_mutex_t mutex;
pthread_cond_t something1;
int protected = 1;

After initializing them, and creating the 2 threads inside the main with pthread_create, i write this:

void *Thread(void *arg)
{
        while(1){
                pthread_mutex_lock(&mutex);

                while(protected == 0){
                        pthread_cond_wait(&something1, &mutex);
                }
                printf("aaa");

                sleep(2);

                pthread_mutex_unlock(&mutex);
        }
        pthread_exit(NULL);

}

void *Thread2(void *arg){
        while(1){
                pthread_mutex_lock(&mutex);

                while(protected == 1){
                        pthread_cond_wait(&something1, &mutex);
                }

                pthread_mutex_unlock(&mutex);
        }
        pthread_exit(NULL);

}

This should just print "aaa" in loop forever, and this works if I remove the sleep(2). If I leave it, the program starts, stays alive, but it prints nothing. Any ideas why this happens?

1 Answers1

3

printf is line buffered, meaning it won't flush the buffer to screen until it reaches a newline "\n", or when the buffer is full. When you don't sleep, the buffer fills up quickly and prints to screen when it gets full, but when you do sleep it will take a long time for the buffer to fill, and so you never see anything on screen. Try changing that to printf("aaa\n");, or add an fflush(stdout); after the printf. See more information here: Why does printf not flush after the call unless a newline is in the format string?

yano
  • 2,550
  • 1
  • 17
  • 29
  • That's correct, with fflush or \n in the printf everything works fine. Thank you, this is very helpful even for my studies. –  Jan 10 '20 at 18:20