gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:24 24 4
gpt4 key购买 nike

<分区>

我正在练习线程编程并发现了这个。当我 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");

}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com