先看第一个程序:
#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;
}
运行结果如下:
当然还有其他办法