进程退出线程即结束的代码验证

本文详细介绍了线程的概念、如何让线程一直输出指定信息而不退出,以及通过使用pthread_join函数阻塞线程实现进程(主线程)不退出的方法。此外,还探讨了线程创建与管理的基本操作,并提供了实际代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看第一个程序:


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


void *show()
{


while(1)
{
printf("ok\n");
}
}


int main()
{
pthread_t tid;

int err;

err=pthread_create(&tid,NULL,show,NULL);

if(err!=0)

{

printf("fail to create\n");

}

return 0;

}运行结果如下:


如何让线程一直输出ok呢,即进程(主线程)不退出


代码如下:


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


void *show()
{


while(1)
{
printf("ok\n");
}
}


int main()
{
pthread_t tid;

int err;

err=pthread_create(&tid,NULL,show,NULL);

if(err!=0)

{

printf("fail to create\n");

}
pthread_join(tid,NULL);//pthread_join函数会阻塞线程

//while(1);使进程一直不退出

return 0;

}

运行结果如下:


当然还有其他办法


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值