c - 为什么这些 printfs 的行为不同?

标签 c multithreading printf

<分区>

我正在练习线程编程并发现了这个。当我 printf("1") 时,输出会在几秒钟后出现,但是当我 printf("\n") 时,输出会逐步出现-步。为什么?

#include<stdio.h>
#include<pthread.h>
#include<errno.h>
#include<stdlib.h>



void * __th_handle(void *);

int run_now=0;      // globle var

int main()
{
    char message[]={"going in thread"};
    void * th_result;
    int ret,c=0;
    pthread_t __th;


//  printf("in main thread\n"); 

    if(pthread_create(&__th,NULL,(void *)__th_handle,(void *)message)==-1)
        {
        perror("pthread_creat fails ");
        exit(0);
        }

    while(c++<20)
    {
        if(run_now==0)
            {
            printf("1");    //printf("1\n");
            run_now=1;
            }
        else
            {sleep(1);}
    }


    pthread_join(__th,&th_result);
    if(ret!=0)
    {
    perror("join fails");
    exit(0);
    }   
    printf("th_result from __th thread : %s\n",(char *)th_result);  

return 0;
}

void * __th_handle(void *argv)
{
//  printf("message : %s",(char *)(argv));
    int c1=0;
    while(c1++<20)
    {
        if(run_now==1)
            {
            printf("2");    //printf("2\n");
            run_now=0;
            }
        else
            {sleep(1);}
    }


    sleep(2);
    pthread_exit("_th thread terminated");

}

最佳答案

stdout 的输出默认是行缓冲的。

如果你添加一个换行符,每个 printf() 都会产生自己的输出。

如果不添加换行符,输出将被累积直到看到换行符或程序结束。这通常会产生单个输出。

关于c - 为什么这些 printfs 的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38334241/

相关文章:

c - 为什么 getchar() 在 printf 语句后读取 '\n'?

c - 执行带有参数的 SQLite 语句

来自多个函数的全局字符串的 C strtok

c - 如何在 32 位汇编中编译?

c++ - 让 QtConcurrent 中的 QTimer 正常工作

java - 线程与单例对象或字符串的同步连接

java - C 或 Python 中的规则引擎

c - 未找到源 chkstk.asm

asp.net-mvc - ASP.NET MVC 中的异步 Controller

java - 在java中使用printf遇到困难并且在eclipse中读取错误