main函数里创建分离线程
int main(int argc, char **argv)
{
pthread_t cli_thread;
ret = pthread_create(&cli_thread, NULL, cli_thread_func, NULL);
if (ret != 0)
{
printf("create cli_thread_func failed\n");
exit(1);
}
}
main函数里创建分离线程,如何避免线程函数cli_thread_func没有执行就退出?
[解决办法]
main函数最后面加死循环。
int main(int argc, char **argv)
{
pthread_t cli_thread;
ret = pthread_create(&cli_thread, NULL, cli_thread_func, NULL);
if (ret != 0)
{
printf("create cli_thread_func failed\n");
exit(1);
}
//1
while(1)
sleep(5);
//2
pthread_join(cli_thread, NULL); // 等待指定线程结束
}
void *cli_thread_func(void *arg)
{
//主业务
finish=true;//结束标为true;
}
int main(int argc, char **argv)
{
bool finish=false;//增加变量判断线程函数是否结束
pthread_t cli_thread;
ret = pthread_create(&cli_thread, NULL, cli_thread_func, NULL);
while(!finish)//等待线程函数结束
{
sleep(1);
}
}