0

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.

NPE
  • 438,426
  • 93
  • 887
  • 970
  • You haven't declared `buffer` as `volatile`, which won't be helping. – Oliver Charlesworth Jan 10 '12 at 15:51
  • 4
    Can you try running `fflush(stdout);` after each call to `printf()` and see if that changes things? – Dan Fego Jan 10 '12 at 15:51
  • If you included the `#include`s required to compile this it would be an excellently asked question – Flexo Jan 10 '12 at 15:52
  • @undur_gongor: I've taken the liberty to reinstate the lack of newline in the second part of the output, since I think it's key to this question (see my answer below). – NPE Jan 10 '12 at 16:05
  • 1
    @oli-charlesworth, there's no need for `volatile` here. Using proper locking functions is enough. Once a function has been called, the compiler must assume `buf` may have changed, and will read it again after waking up. – ugoren Jan 10 '12 at 16:06
  • @Dan Fego: that works. Thanks. – No name is fine too Jan 10 '12 at 16:11

1 Answers1

2

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).

Community
  • 1
  • 1
NPE
  • 438,426
  • 93
  • 887
  • 970