首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

main函数里创办分离线程

2013-11-15 
main函数里创建分离线程int main(int argc, char **argv){pthread_t cli_threadret pthread_create(&cl

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);
}

}
main函数里创建分离线程,如何避免线程函数cli_thread_func没有执行就退出?

[解决办法]
在主线程退出之前等待子线程退出。。。

waitpid
[解决办法]
创建分离线程之后调用在main里pause就行了啊
[解决办法]

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); // 等待指定线程结束 
}

[解决办法]
貌似设置了分离线程的属性后就不能够再join了吧

一般采用如下这样的方式:

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);
    }
}

[解决办法]
试试在main最后调用pthread_exit(NULL);觉得lz的逻辑很奇特,既然在意main退出与否,又为何要创建分离线程...

热点排行