4

I have been facing this problem for not only in this code but also in a few others.

The printf function in placed in a for loop. It should print at every iteration (loop pass). But it prints everything at a stretch after the loop exits.

In the current example, i am using threading. But i have faced the same problem with other programs i have written that did not involve threading.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "threads.h"

ElementPtr RunQ;

void *loop1(void)
{
    int i;
    while(1)
    for(i=1;i<100;i++)
    {
        printf("\t%d",i);
        if(i%8 == 0)
        {
            printf("\n");
            yield(); 
        }
        usleep(500000);
    }
}

void *loop2(void)
{
    int i;
    while(1)
    for(i=201;i<300;i++)
    {
        printf("\t%d",i);
        if(i%4 == 0)
        {
            printf("\n");
            yield(); 
        }
        sleep(1);
    }
}

void *loop3(void)
{
    int i;
    while(1)
    for(i=501;i<600;i++)
    {
        printf("\t%d",i);
        if(i%15 == 0)
        {
            printf("\n");
            yield(); 
        }
        usleep(500000);
    }
}

int main()
{
    InitQueue(&RunQ);

    printf("\nRunning threads:\n");
    start_thread(&loop1);
    start_thread(&loop2);
    start_thread(&loop3);

    run();

    return 0;
}

The output is exactly correct. The only thing is that it is printing every line at once, instead of printing every number one by one. So the first loop would wait 4 seconds and then print 1 to 8 all at once and then switch to thread 2 that waits 4 seconds and then prints and so on.

It should rather print one number at a time. What am I doing wrong?

P.S. I am using gcc compiler on Ubuntu 14.10

halex
  • 15,397
  • 5
  • 50
  • 61
Akshay Kalghatgi
  • 373
  • 1
  • 3
  • 11

2 Answers2

3

The stdout stream is buffered and the numbers you want to print are only displayed when you print the newline.

The solution is to fflush the stdout after each printf.

printf("\t%d",i);
fflush(stdout);

See Why does printf not flush after the call unless a newline is in the format string? for more information

halex
  • 15,397
  • 5
  • 50
  • 61
2

This almost certainly has to do with using buffered output via printf() to stdout.

Take this to your instructor. You're using some kind of private thread interface and it isn't clear whether the thread library involved is smart enough to deal with multiple threads using stdout.

David Ranieri
  • 36,077
  • 6
  • 44
  • 85