#include<stdio.h>
#include<pthread.h>
void handler(void arg)
{
int a=((int)arg);
printf("a:%d\n",a);
fflush(stdout);
return NULL;
}
int main(int argc, char const *argv[])
{
pthread_t tid;
int a=3;
if(pthread_create(&tid,NULL,&handler,&a))
{
perror("pthread_create");
return -1;
}
// pthread_join(tid,NULL);
return 0;
}
这个程序中,由于使用了多线程,主线程在创建子线程之后立即退出,而子线程继续运行,因此可能存在以下两种情况:
- 主线程退出太快,导致子线程没有机会输出内容就被强制退出,从而在终端上看不到输出。这种情况可以通过在主线程调用
pthread_join
函数等待子线程结束后再退出,以确保子线程能够正常运行并输出内容。
pthread_join(tid, NULL);
在主线程中加入上述代码可以等待子线程结束后再退出,这样就能够确保 printf
输出的内容能够被正常显示在终端上。
- 子线程运行得比主线程快,导致主线程退出后子线程还没有来得及输出内容就被强制退出,从而在终端上看不到输出。这种情况可以通过在子线程中加入一些延时操作,以确保子线程有足够的时间来输出内容。
例如,在子线程中可以使用 sleep
函数来让线程休眠一段时间,例如:
void *handler(void *arg)
{
int a = *((int*)arg);
printf("a:%d\n", a);
fflush(stdout);
sleep(1); // 让子线程休眠一秒钟,确保输出能够被正常显示
return NULL;
}
这样可以确保子线程有足够的时间来输出内容,从而避免在终端上看不到输出的情况。