为什么单个链表程序无法按其预期的方式工作

问题描述 投票:0回答:1

我写了一个链表程序。当我尝试打印链接列表时,它的打印效果很好。之后,我在打印功能中引入了延迟(即sleep(1)),以便在1秒钟的时间段后在每个节点上打印输出。但是实际的输出是在经过整个时间后才进行打印(即所有节点都在10秒的时间后进行打印)。您能否解释一下输出中此意外行为的原因是什么?



void print_list(const Node *local_head)
{
    for(const Node *current = local_head; current != NULL; current = current->next) {
        printf("%d -> ", current->value);
        sleep(1);
    }
    printf("\n");
    printf("**** End of List ****\n");
}

int main()
{
    int i;
    Node *head = create_node(10);
    head = append_node(head, create_node(10));
    for(i = 0; i < 10; i++) {
        head = append_node(head, create_node(20));
        head = prepend_node(head, create_node(30));
    }

    print_list(head);

    return 0;
}
c
1个回答
0
投票

stdout的输出(是FILE *写入的printf)是缓冲的。更具体地说,是行缓冲的(连接到终端时)。

这意味着除非刷新缓冲区,否则实际上不会将输出写入终端,这在以下四种情况下发生:FILE *关闭,缓冲区已满,有换行符,或使用fflush功能。

对于您的用例,最佳解决方案是在休眠之前在循环中调用fflush

fflush
© www.soinside.com 2019 - 2024. All rights reserved.