tito-t
Posts: 298
Joined: Thu Jan 07, 2016 5:14 pm

question about printf() in a pthread thread

Thu Oct 20, 2016 8:11 pm

hello,
I encountered an unexpected behaviour in a test program, writing a dot '.' each second in a proprietary pthread thread, just for monitoring that the program is still running:

Code: Select all

volatile int running = 1;

void* thread1Go(void *) {
    unsigned long ms;
    
    ms = millis();    
    while(running) {
        if ((millis()-ms) >=1000) {
            printf(".\n");
            ms=millis();
        }
    }
    return NULL;
    
}
in this case every second a dot is printed, one beyond the other, everything works fine.

but if I exchange
printf(".\n");
by printf(".");
this doesn't happen any more each second, but instead a long time nothing happens,and suddenly a line of several dots like "..........." is printed all at once, not monitoring each 1 sec by a single dot one behind the other.

Why is this so?
Is there a way to force a print-out even without the line feed '\n' in the print cmd?
Last edited by tito-t on Fri Oct 21, 2016 4:27 pm, edited 1 time in total.
- Tim

mutley
Posts: 61
Joined: Sat Jan 02, 2016 8:06 pm

Re: question about ptintf() i a pthread thread

Thu Oct 20, 2016 8:20 pm

The stdout stream is buffered, so will only display what's in the buffer after it reaches a newline (or when it's told to).

So you can :-
1) Flush stdout after each print.
2) Print to stderr that's not buffered.
3) Turn off stdout buffering.

1) fflush(stdout);
2) fprintf(stderr, ".");
3) setbuf(stdout, NULL);

tito-t
Posts: 298
Joined: Thu Jan 07, 2016 5:14 pm

Re: question about printf() in a pthread thread

Thu Oct 20, 2016 8:24 pm

wonderful, thank you very much! fflush(stdout); worked from the start! 8)

BTW, I meanwhile exchanged also the miilis() thing by sleep(1);
- Tim

Return to “C/C++”